<?php
defined('ABSPATH') || exit;
if (!class_exists('yascode_comments')) :
    class yascode_comments
    {
        //init before run
        private static $instance;
        public static function get_instance()
        {
            if (!self::$instance) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        public function __construct()
        {
            add_action('wp_ajax_yascode_send_commentform_ajax', array($this, 'comment_form_send_new_comment'));
            add_action('wp_ajax_nopriv_yascode_send_commentform_ajax', array($this, 'comment_form_send_new_comment'));
            add_action('wp_ajax_yascode_like_dislike_comments', array($this, 'like_dislike_comments'));
            add_action('wp_ajax_nopriv_yascode_like_dislike_comments', array($this, 'like_dislike_comments'));
            add_action('wp_ajax_load_more_post_comments', array($this, 'load_more_post_comments'));
            add_action('wp_ajax_nopriv_load_more_post_comments', array($this, 'load_more_post_comments'));
        }

        public function load_more_post_comments()
        {
            global $post;
            $post = get_post($_POST['post_id']);
            setup_postdata($post);
            $comments = get_comments(array(
                'post_id' => $_POST['post_id'],
                'status' => 'approve'
            ));
            wp_list_comments([
                'page' => $_POST['lastpage'],
                'short_ping' => true,
                'reverse_top_level' => false,
                'per_page' => get_option('comments_per_page'),
                'style' => 'ul',
                'callback' => array($this, 'yascode_post_comment_list')
            ], $comments);
            die;
        }

        public function like_dislike_comments()
        {
            $result = array('success' => false);
            $type = (!empty($_POST['type'])) ? $_POST['type'] : '';
            $comment_id = (!empty($_POST['comment_id'])) ? $_POST['comment_id'] : '';
            if (($type == 'like' || $type == 'dislike') && !empty($comment_id) && is_numeric($comment_id)) {
                if (is_user_logged_in()) $user_id = get_current_user_id();
                else $user_id = get_user_IP();
                $liked_ips = get_comment_meta($comment_id, 'likedislike_ips', true);
                $liked_ips = (!empty($liked_ips)) ? $liked_ips : array();
                if (in_array($user_id, $liked_ips)) $msg = 'شما قبلا نظر خود را ثبت کرده اید';
                else {
                    $last_like = 0;
                    $result['success'] = true;
                    $msg = 'نظر شما ثبت شد';
                    $liked_ips[] = $user_id;
                    update_comment_meta($comment_id, 'likedislike_ips', $liked_ips);
                    if ($type == 'like') {
                        $like_count = get_comment_meta($comment_id, 'count_likes', true);
                        $like_count = (!empty($like_count)) ? $like_count : 0;
                        $like_count = $like_count + 1;
                        update_comment_meta($comment_id, 'count_likes', $like_count);
                        $last_like = $like_count;
                    } elseif ($type == 'dislike') {
                        $dislike_count = get_comment_meta($comment_id, 'count_dislike', true);
                        $dislike_count = (!empty($dislike_count)) ? $dislike_count : 0;
                        $dislike_count = $dislike_count + 1;
                        update_comment_meta($comment_id, 'count_dislike', $dislike_count);
                        $last_like = $dislike_count;
                    }
                }
            } else $msg = 'وضعیت یافت نشد';
            if (!empty($msg)) $result['msg'] = $msg;
            if (!empty($last_like)) $result['last_like'] = $last_like;
            wp_send_json($result);
            wp_die();
        }

        public static function yascode_post_comment_list($comment, $args, $depth)
        {
            $GLOBALS['comment'] = $comment;
            extract($args, EXTR_SKIP);
            if ('div' == $args['style']) $tag = 'div';
            else $tag = 'li';
            $comment_id = get_comment_ID();
            $comment_date = convert_time_to_ago($comment->comment_date);
            $author = get_comment_author();
            $user_ID = get_comment($comment_id)->user_id;
            $like_count = get_comment_meta($comment_id, 'count_likes', true);
            $dislike_count = get_comment_meta($comment_id, 'count_dislike', true);
            $like_count = (!empty($like_count)) ? $like_count : 0;
            $dislike_count = (!empty($dislike_count)) ? $dislike_count : 0;
            if (!empty($user_ID)) {
                $user_data = get_userdata($user_ID);
                $author = (!empty($user_data->display_name)) ? $user_data->display_name : $author;
            }
            $profile = get_user_profile($user_ID, true);
            $comment_spoil = get_comment_meta($comment_id, 'spoil', true); ?>
            <<?php echo $tag ?> <?php comment_class(empty($args['has_children']) ? 'rt comment-item' : 'rt comment-item parent') ?> data-commentid="<?php echo $comment_id; ?>">
                <div class="info right rt-align">
                    <img src="<?php echo $profile; ?>" class="pic rt-50px">
                    <span class="like-dis rt rt-15">
                        <span class="like rt-pointer btn" data-type="like"><span class="c"><?php echo $like_count; ?></span><i class="fa fa-thumbs-up"></i></span>
                        <span class="dislike rt-pointer btn" data-type="dislike"><span class="c"><?php echo $dislike_count; ?></span><i class="fa fa-thumbs-down"></i></span>
                    </span>
                </div>
                <div class="entery left">
                    <div class="name rt rt-13 rt-bold rt-fff"><?php echo $author; ?><span class="rt-400 rt-ddd rt-12"><?php echo $comment_date; ?></span> <a href="#" class="reply rt-30px"><i class="fa fa-reply"></i> پاسخ دادن</a></div>
                    <?php if (!empty($comment->comment_parent)) :
                        $parent_author = get_comment_author($comment->comment_parent);
                        $parent_user_ID = get_comment($comment->comment_parent)->user_id;
                        if (!empty($parent_user_ID)) {
                            $parent_user_data = get_userdata($parent_user_ID);
                            $parent_author = (!empty($parent_user_data->display_name)) ? $parent_user_data->display_name : $parent_author;
                        } ?>
                        <div class="reply-to-user rt">
                            <i class="fa fa-reply"></i>
                            در پاسخ به
                            <?php printf('<samp class="user-name">%s</samp>', $parent_author); ?>
                        </div>
                    <?php endif; ?>
                    <div class="text rt rt-14"><?php comment_text(); ?></div>
                    <?php if ($comment_spoil) : ?>
                        <div class="comment-is-spoil">
                            <span class="btn">نمایش دیدگاه حاوی اسپویل</span>
                        </div>
                    <?php endif; ?>
                    <div class="reply_elem"></div>
                </div>
            </<?php echo $tag; ?>>
<?php
        }

        public function comment_form_send_new_comment()
        {
            $result = array('success' => 0);
            parse_str($_POST["fields"], $_POST);
            if (!wp_verify_nonce($_POST['security_comment'], 'nonce_comment')) {
                $result['message'] = 'خطایی پیش آمد در فرصتی دیگر امتحان کنید !';
                wp_send_json($result);
                wp_die();
            }
            $post_id = (!empty($_POST['post_id']) && is_numeric($_POST['post_id'])) ? $_POST['post_id'] : 0;
            $user_id = (is_user_logged_in()) ? get_current_user_id() : 0;
            $ip = get_user_IP();
            $useragent = $_SERVER['HTTP_USER_AGENT'];
            if (is_user_logged_in()) {
                $user_data = get_user_by('id', $user_id);
                $email = (!empty($user_data->user_email)) ? $user_data->user_email : '';
                $author = (!empty($user_data->user_login)) ? $user_data->user_login : '';
            } else {
                $author = (!empty(sanitize_text_field($_POST['author_comment']))) ? sanitize_text_field($_POST['author_comment']) : '';
                $email = (!empty(sanitize_text_field($_POST['author_email']))) ? rtrim(sanitize_text_field($_POST['author_email'])) : '';
            }
            $comment = (!empty(sanitize_textarea_field($_POST['content_comment']))) ? sanitize_textarea_field($_POST['content_comment']) : '';
            $coment_parent_id = (!empty($_POST['parent_comment_id']) && is_numeric($_POST['parent_comment_id'])) ? $_POST['parent_comment_id'] : 0;
            $comment_spoil = (!empty($_POST['spoil_comment'])) ? 1 : 0;
            $time = date('Y-m-d H:i:s');
            $registration = get_option('comment_registration');
            if ($registration && !is_user_logged_in()) {
                $result['message'] = 'برای ثبت دیدگاه باید وارد حساب کاربری شوید';
                wp_send_json($result);
                wp_die();
            }
            if (!comments_open($post_id)) {
                $result['message'] = 'دیدگاه ها بسته می باشد';
                wp_send_json($result);
                wp_die();
            }
            if (empty($author)) {
                $result['message'] = 'لطفا نام خود را وارد نمایید';
                wp_send_json($result);
                wp_die();
            }
            if (empty($email)) {
                $result['message'] = 'لطفا ایمیل خود را وارد نمایید';
                wp_send_json($result);
                wp_die();
            }
            if (!is_email($email)) {
                $result['message'] = 'لطفا یک ایمیل واقعی وارد کنید';
                wp_send_json($result);
                wp_die();
            }
            if (empty($comment)) {
                $result['message'] = 'دیدگاه نمی تواند خالی باشد';
                wp_send_json($result);
                wp_die();
            }
            $moderation = get_option('comment_moderation');
            $moderation = (!empty($moderation)) ? 1 : 0;
            $data = array(
                'comment_post_ID' => $post_id,
                'comment_author' => $author,
                'comment_author_email' => $email,
                'comment_author_url' => '',
                'comment_content' => $comment,
                'comment_type' => '',
                'comment_parent' => $coment_parent_id,
                'user_id' => $user_id,
                'comment_author_IP' => $ip,
                'comment_agent' => $useragent,
                'comment_date' => $time,
                'comment_approved' => 1 - $moderation,
            );
            $comment_id = wp_insert_comment($data);
            if (!empty($comment_spoil)) {
                update_comment_meta($comment_id, 'spoil', 1);
            }
            $result = array(
                'success' => 1,
                'message' => 'دیدگاه شما با موفقیت ارسال شد',
                'post_id' => $comment_id,
                'last' => $comment,
            );
            $result['message'] = ($moderation == 1)  ? 'دیدگاه پس از بررسی منتشر میشود !' : $result['message'];
            wp_send_json($result);
            wp_die();
        }
    }
    yascode_comments::get_instance();
endif;
