<?php

// Ensure the file is being run within the WordPress environment
if ( !defined( 'ABSPATH' ) ) {
    exit;
    // Exit if accessed directly
}
// Enqueue styles and scripts for post ratings
add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script( 'jquery' );
    wp_enqueue_style( 'bootstrap-css', plugins_url( '/css/bootstrap.min.css', __FILE__ ) );
    wp_enqueue_style( 'font-awesome-css', plugins_url( '/css/font-awesome.min.css', __FILE__ ) );
    wp_enqueue_style( 'quill-css', plugins_url( '/css/quill.snow.css', __FILE__ ) );
    wp_enqueue_style( 'custom-style', plugins_url( '/css/erbwp-user.css', __FILE__ ) );
    wp_enqueue_script(
        'bootstrap-js',
        plugins_url( '/js/bootstrap.bundle.min.js', __FILE__ ),
        array('jquery'),
        '4.5.2',
        true
    );
    wp_enqueue_script(
        'quill-js',
        plugins_url( '/js/quill.js', __FILE__ ),
        array('jquery'),
        null,
        true
    );
    wp_enqueue_script(
        'erbwp-rating',
        plugins_url( '/js/erbwp-user.js', __FILE__ ),
        array('jquery'),
        null,
        true
    );
    wp_localize_script( 'erbwp-rating', 'erbwp_ajax', array(
        'url'                  => admin_url( 'admin-ajax.php' ),
        'nonce'                => wp_create_nonce( 'erbwp_ajax_nonce' ),
        'messageHoldForReview' => get_option( 'erbwp_hold_for_review_comment_with_x_links_message' ),
    ) );
} );
function erbwp_dynamic_css() {
    $modal_header_background_color = get_option( 'erbwp_modal_header_background_color', '#007bff' );
    $modal_header_color = get_option( 'erbwp_modal_header_color', '#007bff' );
    $custom_css = "\n    .modal-header-custom {\n        background-color: {$modal_header_background_color};\n    }\n    \n    .modal-title-custom {\n        color: {$modal_header_color};\n    }\n    ";
    wp_add_inline_style( 'custom-style', wp_kses_post( $custom_css ) );
}

add_action( 'wp_enqueue_scripts', 'erbwp_dynamic_css' );
function erbwp_add_query_vars(  $vars  ) {
    $vars[] = "erbwp_page";
    return $vars;
}

add_filter( 'query_vars', 'erbwp_add_query_vars' );
function erbwp_add_rating_system(  $content  ) {
    $enabledFor = get_option( 'erbwp_enabled_for' );
    $enableForArr = [];
    if ( $enabledFor == 'none' ) {
        return $content;
    } else {
        if ( $enabledFor == 'post' ) {
            $enableForArr = ['post'];
        } else {
            if ( $enabledFor == 'page' ) {
                $enableForArr = ['page'];
            } else {
                if ( $enabledFor == 'both' ) {
                    $enableForArr = ['post', 'page'];
                }
            }
        }
    }
    if ( is_singular( $enableForArr ) ) {
        $rating_label = get_option( 'erbwp_rating_label', 'Rating' );
        $submit_label = get_option( 'erbwp_submit_label', 'Submit' );
        $header_success_label = get_option( 'erbwp_header_success_label', 'Your rating was successfully saved' );
        $header_fail_label = get_option( 'erbwp_header_fail_label', 'Your rating was not saved' );
        $success_message_label = get_option( 'erbwp_success_message', 'Thanks for your rating' );
        $fail_message_label = get_option( 'erbwp_fail_label', 'Cannot save your rating. Please try it again later' );
        $header_remind_rating_label = get_option( 'erbwp_header_remind_rating_label', 'We value your feedback! ⭐' );
        $remind_rating_message_label = get_option( 'erbwp_remind_rating_message_label', 'If you enjoyed this post or found it helpful, please take a moment to rate it. Your feedback helps us improve and provide more of the content you love. Thank you!' );
        $post_id = get_the_ID();
        global $wpdb;
        $ratings = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}reviews WHERE post_id = %d", $post_id ) );
        $average_rating = ( !empty( $ratings ) ? round( array_sum( array_column( $ratings, 'rating' ) ) / count( $ratings ), 2 ) : 'No ratings' );
        $ratings_count = ( !empty( $ratings ) ? count( $ratings ) : 0 );
        $captchaHTML = '';
        $content .= '
        <div id="erbwp-rating">
            <h3>' . $rating_label . '</h3>
            <span id="erbwp-average-rating">' . 'Average Rating: ' . $average_rating . ' - ' . $ratings_count . ' Ratings</span>
            <form id="erbwp-rating-form" data-post-id="' . $post_id . '">
                <fieldset class="rating">
                    <input type="radio" id="star1" name="rating" value="1" />
                    <label class="star" for="star1" title="1 star"><i class="fa fa-star fa-lg"></i></label>
                    <input type="radio" id="star2" name="rating" value="2" />
                    <label class="star" for="star2" title="2 stars"><i class="fa fa-star fa-lg"></i></label>
                    <input type="radio" id="star3" name="rating" value="3" />
                    <label class="star" for="star3" title="3 stars"><i class="fa fa-star fa-lg"></i></label>
                    <input type="radio" id="star4" name="rating" value="4" />
                    <label class="star" for="star4" title="4 stars"><i class="fa fa-star fa-lg"></i></label>
                    <input type="radio" id="star5" name="rating" value="5" />
                    <label class="star" for="star5" title="5 stars"><i class="fa fa-star fa-lg"></i></label>
                </fieldset>

                <label for="erbwp-name">Name <span class="required-asterisk">*</span></label>
                <input type="text" id="erbwp-name" name="name" class="form-control" required />

                <label for="erbwp-email">Email <span class="required-asterisk">*</span></label>
                <input type="email" id="erbwp-email" name="email" class="form-control" required />

                <label for="comment-editor">Comment <span class="required-asterisk">*</span></label>
                <div id="comment-editor"></div>
                <div id="quill-error-message" style="color: red; display: none;">Please enter a comment.</div>
                <input type="text" id="erbwp-replyToCommentId" name="replyToCommentId" class="form-control" hidden/>
                ' . $captchaHTML . '<button type="submit" class="btn btn-primary mt-3 mb-3 w-100">' . $submit_label . '</button>
            </form>

            <div id="ratings-container"></div>

            <div id="notifications"></div>

            <div class="modal fade" id="ratingSuccessModal" tabindex="-1" role="dialog" aria-labelledby="ratingSuccessModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                        <div class="modal-header modal-header-custom">
                            <h5 class="modal-title modal-title-custom" id="ratingSuccessModalLabel">' . $header_success_label . '</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <p>' . $success_message_label . '</p>
                            <p id="extend-message"></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="ratingFailModal" tabindex="-1" role="dialog" aria-labelledby="ratingFailModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                        <div class="modal-header modal-header-custom">
                            <h5 class="modal-title modal-title-custom" id="ratingFailModalLabel">' . $header_fail_label . '</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <p>' . $fail_message_label . '</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="remindRating" tabindex="-1" role="dialog" aria-labelledby="remindRatingLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                        <div class="modal-header modal-header-custom">
                            <h5 class="modal-title modal-title-custom" id="remindRatingLabel">' . $header_remind_rating_label . '</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <p>' . $remind_rating_message_label . '</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        ';
    }
    return $content;
}

add_filter( 'the_content', 'erbwp_add_rating_system' );
// Save the rating to the database
function erbwp_save_rating() {
    check_ajax_referer( 'erbwp_ajax_nonce', 'nonce' );
    if ( isset( 
        $_POST['rating'],
        $_POST['post_id'],
        $_POST['email'],
        $_POST['name']
     ) ) {
        $rating = intval( sanitize_text_field( $_POST['rating'] ) );
        $post_id = intval( sanitize_text_field( $_POST['post_id'] ) );
        $comment = wp_kses_post( $_POST['comment'] );
        $email = sanitize_email( $_POST['email'] );
        $name = sanitize_text_field( $_POST['name'] );
        $userId = ( get_current_user_id() ? get_current_user_id() : null );
        $date = current_time( 'mysql' );
        $parent_id = sanitize_text_field( $_POST['parent_id'] );
        $is_hidden = false;
        $hidden_reason = null;
        $holdForReviewWithXLinks = get_option( 'erbwp_hold_for_review_comment_with_x_links' );
        if ( $holdForReviewWithXLinks && (int) $holdForReviewWithXLinks <= erbwp_countLinks( $comment ) ) {
            $is_hidden = true;
            $hidden_reason = get_option( "erbwp_hold_for_review_comment_with_x_links_message" );
        }
        if ( erbwp_checkBlacklistKeyword( $comment ) ) {
            $is_hidden = true;
            $hidden_reason = get_option( "erbwp_hold_for_review_comment_with_blacklist_keyword_message" );
        }
        global $wpdb;
        $table_name = $wpdb->prefix . 'reviews';
        $wpdb->insert( $table_name, [
            'post_id'       => $post_id,
            'rating'        => $rating,
            'comment'       => $comment,
            'date'          => $date,
            'email'         => $email,
            'name'          => $name,
            'user_id'       => $userId,
            'parent_id'     => $parent_id,
            'is_hidden'     => $is_hidden,
            'hidden_reason' => $hidden_reason,
        ] );
        $reviews = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}reviews WHERE post_id = %d AND rating != %d", $post_id, 0 ) );
        // Calculate the new average rating
        $average_rating = array_sum( array_column( $reviews, 'rating' ) ) / count( $reviews );
        // Save the average rating to post meta
        update_post_meta( $post_id, 'average_rating', round( $average_rating, 2 ) );
        // Send notification email
        erbwp_send_notify_email( $post_id, $comment, $name );
        wp_send_json_success( [
            'average_rating' => round( $average_rating, 2 ),
            'ratings_count'  => count( $reviews ),
            'message'        => 'Thanks for your rating',
            'is_hidden'      => $is_hidden,
            'hidden_reason'  => $hidden_reason,
        ] );
    }
    wp_send_json_error( 'An error occurred while saving the rating.' );
}

add_action( 'wp_ajax_erbwp_save_rating', 'erbwp_save_rating' );
add_action( 'wp_ajax_nopriv_erbwp_save_rating', 'erbwp_save_rating' );
function erbwp_send_notify_email(  $post_id, $comment, $comment_author  ) {
    $isSendNotifyToAdmin = get_option( 'erbwp_send_email_notify_to_admin_when_new_rating' );
    $isSendNotifyToAuthor = get_option( 'erbwp_send_email_notify_to_author_when_new_rating' );
    if ( !$isSendNotifyToAdmin && !$isSendNotifyToAuthor ) {
        return;
    }
    $author_id = get_post_field( 'post_author', $post_id );
    $author_data = get_userdata( $author_id );
    $author_email = $author_data->user_email;
    $author_name = $author_data->display_name;
    // Get the admin email
    $admin_email = get_option( 'admin_email' );
    // Email subject
    $subject = "New Comment on Your Post!";
    // Email message
    $post_title = get_the_title( $post_id );
    $post_link = get_permalink( $post_id );
    $website_name = get_bloginfo( 'name' );
    $message = "";
    $message .= "<!DOCTYPE html>";
    $message .= "<html>";
    $message .= "<head>";
    $message .= "<title>New Comment Notification</title>";
    $message .= "</head>";
    $message .= "<body>";
    $message .= "<table width='600' align='center' border='1' cellpadding='20' cellspacing='0' bgcolor='#f9f9f9' bordercolor='#ccc'>";
    $message .= "<tr bgcolor='#4CAF50'>";
    $message .= "<td align='center' text='white'>";
    $message .= "<h1>New Comment Notification</h1>";
    $message .= "</td>";
    $message .= "</tr>";
    $message .= "<tr>";
    $message .= "<td>";
    $message .= "<p>Hello {$author_name},</p>";
    $message .= "<p>A new comment has been posted on your article titled <b>{$post_title}</b></p>";
    $message .= "<p><b>Comment by:</b> <i>{$comment_author}</i></p>";
    $message .= "<p><b>Comment:</b></p>";
    $message .= "<blockquote>{$comment}</blockquote>";
    $message .= "<p>To view the comment, click <a href='{$post_link}'>here</a>.</p>";
    $message .= "</td>";
    $message .= "</tr>";
    $message .= "<tr>";
    $message .= "<td align='center'>";
    $message .= "<font size='2' color='#777'>";
    $message .= "<p>Thank you for using {$website_name}.</p>";
    $message .= "</font>";
    $message .= "</td>";
    $message .= "</tr>";
    $message .= "</table>";
    $message .= "</body>";
    $message .= "</html>";
    // Additional headers
    $headers = array('Content-Type: text/html; charset=UTF-8');
    // Recipients
    if ( $isSendNotifyToAdmin ) {
        $to[] = $admin_email;
    }
    if ( $isSendNotifyToAuthor ) {
        $to[] = $author_email;
    }
    // Prepare the email data
    $email_data = array(
        'to'      => $to,
        'subject' => $subject,
        'message' => $message,
        'headers' => $headers,
    );
    // Schedule the email to be sent
    wp_schedule_single_event( time(), 'erbwp_send_scheduled_email_action', array($email_data) );
}

function erbwp_countLinks(  $comment  ) {
    $comment = sanitize_text_field( $comment );
    // Use a regular expression to match all URLs in the sanitized comment
    $link_count = preg_match_all( '/\\bhttps?:\\/\\/\\S+/i', $comment, $matches );
    return $link_count;
}

function erbwp_checkBlacklistKeyword(  $comment  ) {
    // Retrieve the option value
    $blacklistOption = get_option( 'erbwp_blacklist_keyword' );
    // Check if the option is null or empty
    if ( is_null( $blacklistOption ) || $blacklistOption === '' ) {
        error_log( "Blacklist option is null or empty." );
        return false;
        // No keywords to check against
    }
    // Process the option value
    $blacklistedKeywords = array_filter( array_map( 'trim', explode( ";", $blacklistOption ) ) );
    // Check if the comment contains any blacklisted keywords
    $containsBlacklistedKeyword = false;
    foreach ( $blacklistedKeywords as $keyword ) {
        if ( stripos( $comment, $keyword ) !== false ) {
            $containsBlacklistedKeyword = true;
            break;
        }
    }
    return $containsBlacklistedKeyword;
}

function erbwp_load_ratings() {
    check_ajax_referer( 'erbwp_ajax_nonce', 'nonce' );
    $currentPage = ( isset( $_POST['erbwp_page'] ) ? intval( sanitize_text_field( $_POST['erbwp_page'] ) ) : 1 );
    global $wpdb;
    $table_name = $wpdb->prefix . 'reviews';
    $post_id = sanitize_text_field( $_POST['postId'] );
    $sortDirection = ( get_option( 'erbwp_sort_ratings_direction' ) == 'Newest_First' ? 'DESC' : 'ASC' );
    $ratings = [];
    if ( $sortDirection == 'ASC' ) {
        $ratings = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}reviews WHERE post_id = %d AND parent_id = 0 ORDER BY date ASC", $post_id ) );
    } else {
        $ratings = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}reviews WHERE post_id = %d AND parent_id = 0 ORDER BY date DESC", $post_id ) );
    }
    $ratingsJson = [];
    if ( !empty( $ratings ) ) {
        $ratingsPerPage = get_option( 'erbwp_ratings_per_page' );
        $totalRatings = count( $ratings );
        $totalPages = ceil( $totalRatings / $ratingsPerPage );
        $avatarURLDefault = get_option( 'erbwp_avatar_url_default' );
        // Calculate the starting and ending index of ratings to display on the current page
        $startIndex = ($currentPage - 1) * $ratingsPerPage;
        $endIndex = $startIndex + $ratingsPerPage;
        // Slice the ratings array based on the current page
        $ratingsToDisplay = array_slice( $ratings, $startIndex, $ratingsPerPage );
        foreach ( $ratingsToDisplay as $rating ) {
            $post_author_id = get_post_field( 'post_author', $post_id );
            $current_user_id = get_current_user_id();
            $email = $rating->email;
            $avatarURL = get_avatar_url( $email );
            $avatarURL = ( $avatarURL != null ? $avatarURL : $avatarURLDefault );
            $id = $rating->id;
            $reply_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}reviews WHERE parent_id = %d", $id ) );
            $isAdmin = current_user_can( 'administrator' );
            $isAuthor = $current_user_id == $post_author_id;
            $finalComment = $rating->comment;
            if ( $rating->is_hidden == "1" && !$isAdmin && !$isAuthor ) {
                $finalComment = 'This comment has been hidden.';
            }
            $ratingsJson['reviews'][] = [
                'id'          => $rating->id,
                'authorName'  => $rating->name,
                'ratingValue' => $rating->rating,
                'isHidden'    => $rating->is_hidden == "1",
                'isAdmin'     => $isAdmin,
                'isAuthor'    => $isAuthor,
                'comment'     => wp_kses_post( $finalComment ),
                'childCount'  => $reply_count,
                'avatarURL'   => esc_url( $avatarURL ),
                'date'        => $rating->date,
            ];
        }
        $ratingsJson['pagination'] = [
            'currentPage' => $currentPage,
            'totalPages'  => $totalPages,
        ];
    } else {
        $ratingsJson['reviews'] = [];
        $ratingsJson['pagination'] = [
            'currentPage' => $currentPage,
            'totalPages'  => 0,
        ];
    }
    wp_send_json_success( $ratingsJson );
    wp_die();
    // Terminate to avoid appending a 0 to the AJAX response
}

add_action( 'wp_ajax_load_ratings', 'erbwp_load_ratings' );
add_action( 'wp_ajax_nopriv_load_ratings', 'erbwp_load_ratings' );
function erbwp_load_reply_comment() {
    check_ajax_referer( 'erbwp_ajax_nonce', 'nonce' );
    global $wpdb;
    $table_name = $wpdb->prefix . 'reviews';
    $parent_id = sanitize_text_field( $_POST['parentId'] );
    $sortDirection = ( get_option( 'erbwp_sort_ratings_direction' ) == 'Newest_First' ? 'DESC' : 'ASC' );
    $ratings = [];
    if ( $sortDirection == 'ASC' ) {
        $ratings = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}reviews WHERE parent_id = %d ORDER BY date ASC", $parent_id ) );
    } else {
        $ratings = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}reviews WHERE parent_id = %d ORDER BY date DESC", $parent_id ) );
    }
    $ratingsJson = [];
    $currentPage = 1;
    if ( !empty( $ratings ) ) {
        $avatarURLDefault = get_option( 'erbwp_avatar_url_default' );
        foreach ( $ratings as $rating ) {
            $post_author_id = get_post_field( 'post_author', $post_id );
            $current_user_id = get_current_user_id();
            $email = $rating->email;
            $avatarURL = get_avatar_url( $email );
            $avatarURL = ( $avatarURL != null ? $avatarURL : $avatarURLDefault );
            $id = $rating->id;
            $reply_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}reviews WHERE parent_id = %d", $id ) );
            $isAdmin = current_user_can( 'administrator' );
            $isAuthor = $current_user_id == $post_author_id;
            $finalComment = $rating->comment;
            if ( $rating->is_hidden == "1" && !$isAdmin && !$isAuthor ) {
                $finalComment = 'This comment has been hidden.';
            }
            $ratingsJson['reviews'][] = [
                'id'          => $rating->id,
                'authorName'  => $rating->name,
                'ratingValue' => $rating->rating,
                'isHidden'    => $rating->is_hidden == "1",
                'isAdmin'     => $isAdmin,
                'isAuthor'    => $isAuthor,
                'comment'     => $finalComment,
                'childCount'  => $reply_count,
                'avatarURL'   => $avatarURL,
                'date'        => $rating->date,
            ];
        }
    } else {
        $ratingsJson['reviews'] = [];
        $ratingsJson['pagination'] = [
            'currentPage' => $currentPage,
            'totalPages'  => 0,
        ];
    }
    wp_send_json_success( $ratingsJson );
    wp_die();
    // Terminate to avoid appending a 0 to the AJAX response
}

add_action( 'wp_ajax_load_reply_comment', 'erbwp_load_reply_comment' );
add_action( 'wp_ajax_nopriv_load_reply_comment', 'erbwp_load_reply_comment' );
function erbwp_calculate_reading_time() {
    $isRemindRating = get_option( 'erbwp_remind_rating' );
    check_ajax_referer( 'erbwp_ajax_nonce', 'nonce' );
    $post_id = sanitize_text_field( $_POST['postId'] );
    $post = get_post( $post_id );
    $content = $post->post_content;
    $word_count = str_word_count( strip_tags( $content ) );
    $readingSpeedPerSecond = 225 / 60;
    // Convert reading speed to words per second
    $readingTimeInMiliSeconds = ceil( $word_count / $readingSpeedPerSecond * 1000 );
    $response = array(
        "isRemindRating"           => $isRemindRating,
        "readingTimeInMiliSeconds" => $readingTimeInMiliSeconds,
    );
    header( 'Content-Type: application/json' );
    echo wp_json_encode( $response );
    wp_die();
    // Terminate to avoid appending a 0 to the AJAX response
}

add_action( 'wp_ajax_calculate_reading_time', 'erbwp_calculate_reading_time' );
add_action( 'wp_ajax_nopriv_calculate_reading_time', 'erbwp_calculate_reading_time' );