<?php
$optionReview = get_option('bbpc_notify_review');
if ( is_admin() && time() >= (int) $optionReview && $optionReview !== '0') {
    add_action('admin_enqueue_scripts', 'forumax_notify_enqueue_script'); // Hook to admin_enqueue_scripts

    $bbpc_installed = get_option('bbpc_installed');
    // Check if timestamp exists
    if ( $bbpc_installed ) {
        // Add 7days to the timestamp
        $show_notice = $bbpc_installed + (7 * 24 * 60 * 60);

        // Get the current time
        $current_time = current_time('timestamp');

        // Compare current time with timestamp + 7 days
        if ( $current_time >= $show_notice ) {
            add_action('admin_notices', 'forumax_notify_give_review');
        }
    }
}

function forumax_notify_enqueue_script() {
    wp_enqueue_script( 'bbpc-notify-review' );
}

add_action('wp_ajax_bbpc_notify_save_review', 'forumax_notify_save_review');

/**
 ** Give Notice
 **/
function forumax_notify_give_review() {
	$forums = get_pages( [
		'post_type'   => 'forum',
		'post_status' => 'publish'
	] );
	$forums = is_array( $forums ) ? $forums : [];

	$topics = get_pages( [
		'post_type'   => 'topic',
		'post_status' => 'publish'
	] );
	$topics = is_array( $topics ) ? $topics : [];
	?>
    <div class="notice notice-success is-dismissible" id="bbpc_notify_review">
		<div>
			<img src="<?php echo esc_url( FORUMAX_ASSETS . 'img/logo.svg' ); ?>"> 
		</div>
		<div>
			<h3><?php esc_html_e( 'Give Forumax a review', 'forumax' ); ?></h3>
			<p style="margin-top: 10px;">
				<?php
				if ( count( $forums ) <= 0 ) {
					esc_html_e( 'Thank you for choosing Forumax. We hope you love it. Could you take a couple of seconds posting a nice review to share your happy experience?', 'forumax' );
				} else {
					$topics_count = count( $topics );
					$topics_text  = $topics_count > 0 ? " and <b>" . $topics_count . "</b> topics" : '';
					echo wp_kses(
						sprintf(
						/* translators: 1: number of forums created, 2: additional topics text */
							__( 'You have created <b>%1$d</b> forums%2$s with Forumax. That\'s awesome! May we ask you to give it a 5-Star rating on WordPress? <br> It will help us spread the word and boost our motivation.', 'forumax' ),
							count( $forums ),
							$topics_text
						),
						array(
							'b'      => array(), // Allow <b> tag
							'strong' => array(), // If needed, allow <strong> tag
							'br'     => array(), // If needed, allow <br> tag
						)
					);
				}
				?>
			</p>
			<p class="bbpc_notify_review_subheading" style="margin-bottom: 12px;">
				<?php esc_html_e( 'We will be forever grateful. Thank you in advance.', 'forumax' ); ?>
			</p>
			<div class="action_links">
				<a href="javascript:;" data="rateNow" class="button button-primary" style="margin-right: 5px">
					<?php esc_html_e( 'Ok, you deserve', 'forumax' ) ?>
					<span class='icon_star'></span>
					<span class='icon_star'></span>
					<span class='icon_star'></span>
					<span class='icon_star'></span>
					<span class='icon_star'></span>
				</a>
				<a href="javascript:;" class="btn" data="later" style="margin-right: 5px"> 
					<span class='icon_clock_alt'></span>
					<?php esc_html_e( 'Nope, maybe later', 'forumax' ) ?> 
				</a>
				<a href="javascript:;" class="btn red" data="alreadyDid">
					<span class='icon_close_alt2'></span>
					<?php esc_html_e( 'Never show again', 'forumax' ) ?> 
				</a>
			</div>
		</div>
    </div>

    <script>
        jQuery(document).ready(function () {
            // Show review popup
            jQuery("#bbpc_notify_review a").on("click", function () {
                const thisElement = this;
                const fieldValue = jQuery(thisElement).attr("data");
                const freeLink = "https://wordpress.org/support/plugin/bbp-core/reviews/#new-post";
                let hidePopup = false;
                if ( fieldValue === "rateNow" ) {
                    window.open(freeLink, "_blank");
                } else {
                    hidePopup = true;
                }

                jQuery
                    .ajax({
                        dataType: 'json',
                        url: forumax_local_object.ajaxurl,
                        type: "post",
                        data: {
                            action: "bbpc_notify_save_review",
                            field: fieldValue,
                            nonce: forumax_local_object.nonce,
                        },
                    })
                    .done(function (result) {
                        if (hidePopup == true) {
                            jQuery("#bbpc_notify_review .notice-dismiss").trigger("click");
                        }
                    })
                    .fail(function (res) {
                        if (hidePopup == true) {
                            console.log(res.responseText);
                            jQuery("#bbpc_notify_review .notice-dismiss").trigger("click");
                        }
                    });
            })
        })
    </script>
	<?php
}

/**
 ** Save Notice
 **/
function forumax_notify_save_review() {
	if ( isset( $_POST ) ) {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : null;
		$field = isset( $_POST['field'] ) ? sanitize_text_field( wp_unslash( $_POST['field'] ) ) : null;

		if ( ! wp_verify_nonce( $nonce, 'bbpc-admin-nonce' ) ) {
			wp_send_json_error( array( 'status' => 'Wrong nonce validate!' ) );
			exit();
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized user' ) );
			exit();
		}

		if ( $field == 'later' ) {
			update_option( 'bbpc_notify_review', time() + 3 * 60 * 60 * 24 ); //After 3 days show
		} else if ( $field == 'alreadyDid' ) {
			update_option( 'bbpc_notify_review', 0 );
		}
		wp_send_json_success();
	}
	wp_send_json_error( array( 'message' => 'Update fail!' ) );
}
