<?php
/**
 * Review Prompt — ethical, dismissable prompt for WordPress.org reviews.
 *
 * Self-registering: instantiate once and all hooks are set up automatically.
 * Does NOT modify any existing functionality — purely additive.
 *
 * Triggers after:
 *   - 5 completed bookings (wahrb_bookings_milestone option), OR
 *   - 30 days after activation (wahrb_activated_date option)
 *
 * Never shows again once dismissed (wahrb_review_dismissed option).
 *
 * @package WahraRentalsBookings
 * @since   2.0.6
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class WAHRB_Review_Prompt
 */
class WAHRB_Review_Prompt {

	/**
	 * Review URL on WordPress.org.
	 *
	 * @var string
	 */
	private string $review_url = 'https://wordpress.org/support/plugin/wahra-rentals-bookings/reviews/#new-post';

	/**
	 * Minimum completed bookings before prompt.
	 *
	 * @var int
	 */
	private int $booking_threshold = 5;

	/**
	 * Days after activation before prompt.
	 *
	 * @var int
	 */
	private int $days_threshold = 30;

	/**
	 * Constructor — register hooks.
	 */
	public function __construct() {
		add_action( 'admin_notices', array( $this, 'maybe_show_review_prompt' ) );
		add_action( 'wp_ajax_wahrb_dismiss_review', array( $this, 'ajax_dismiss_review' ) );
		add_action( 'admin_footer', array( $this, 'dismiss_script' ) );

		// Record activation date on first load if not set.
		if ( false === get_option( 'wahrb_activated_date' ) ) {
			update_option( 'wahrb_activated_date', time(), true );
		}

		// Hook into booking completion to track count.
		add_action( 'wahrb_booking_status_changed', array( $this, 'track_completed_bookings' ), 99, 3 );
	}

	/**
	 * Track completed bookings for the milestone threshold.
	 *
	 * @param int    $booking_id  Booking ID.
	 * @param string $new_status  New status.
	 * @param string $old_status  Old status.
	 */
	public function track_completed_bookings( int $booking_id, string $new_status, string $old_status ): void {
		if ( 'completed' !== $new_status ) {
			return;
		}

		$count = (int) get_option( 'wahrb_bookings_milestone', 0 );
		update_option( 'wahrb_bookings_milestone', $count + 1, true );
	}

	/**
	 * Determine if conditions are met and show the review prompt.
	 */
	public function maybe_show_review_prompt(): void {
		// Already dismissed — never show again.
		if ( get_option( 'wahrb_review_dismissed' ) ) {
			return;
		}

		// Only show to admins.
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Check booking milestone.
		$bookings_met = ( (int) get_option( 'wahrb_bookings_milestone', 0 ) ) >= $this->booking_threshold;

		// Check time-based threshold.
		$activated    = (int) get_option( 'wahrb_activated_date', 0 );
		$days_met     = $activated > 0 && ( time() - $activated ) >= ( $this->days_threshold * DAY_IN_SECONDS );

		if ( ! $bookings_met && ! $days_met ) {
			return;
		}

		printf(
			'<div class="notice notice-info is-dismissible wahrb-review-prompt" data-nonce="%1$s">
				<p>%2$s</p>
				<p>
					<a href="%3$s" target="_blank" class="button button-primary">%4$s</a>
					<a href="#" class="wahrb-dismiss-review" style="margin-left:12px;">%5$s</a>
				</p>
			</div>',
			esc_attr( wp_create_nonce( 'wahrb_dismiss_review' ) ),
			esc_html__( 'Enjoying Rentals & Bookings for WooCommerce? You\'ve been using the plugin successfully — would you mind leaving a quick review? It helps other store owners discover the plugin!', 'wahra-rentals-bookings' ),
			esc_url( $this->review_url ),
			esc_html__( 'Leave a ★★★★★ Review', 'wahra-rentals-bookings' ),
			esc_html__( 'No thanks, dismiss forever', 'wahra-rentals-bookings' )
		);
	}

	/**
	 * AJAX handler — dismiss the review prompt permanently.
	 */
	public function ajax_dismiss_review(): void {
		check_ajax_referer( 'wahrb_dismiss_review', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}

		update_option( 'wahrb_review_dismissed', true, true );
		wp_send_json_success();
	}

	/**
	 * Print inline JS to handle dismiss clicks.
	 */
	public function dismiss_script(): void {
		if ( get_option( 'wahrb_review_dismissed' ) ) {
			return;
		}
		?>
		<script>
		(function(){
			document.addEventListener('click', function(e) {
				if (!e.target.classList.contains('wahrb-dismiss-review')) return;
				e.preventDefault();
				var wrap = e.target.closest('.wahrb-review-prompt');
				if (!wrap) return;
				var nonce = wrap.getAttribute('data-nonce');
				var xhr = new XMLHttpRequest();
				xhr.open('POST', ajaxurl);
				xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				xhr.send('action=wahrb_dismiss_review&nonce=' + encodeURIComponent(nonce));
				wrap.style.display = 'none';
			});
		})();
		</script>
		<?php
	}
}
