<?php
/**
 * Flipa — WordPress.org review nudge.
 *
 * One gentle, dismissible admin notice asking happy FREE users to leave a
 * WordPress.org review. Shown only after the user has created a flipbook and
 * used the plugin for a little while, and NEVER to paying customers
 * (flipa_fs()->is_paying() is true for Pro + for the marketplace stub build,
 * so this naturally appears only in the free/.org build).
 *
 * All output is escaped; all state changes are nonce-checked (WP.org compliant).
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }

class Flipa_Review_Nudge {

	const REVIEW_URL  = 'https://wordpress.org/support/plugin/flipa-pdf-flipbook/reviews/#new-post';
	const MIN_DAYS    = 10;                    // wait this many days after install before asking
	const SNOOZE_DAYS = 14;                    // "Maybe later" snooze length
	const OPT_INSTALL = 'flipa_installed_at';  // site option: first-seen timestamp
	const META_STATE  = 'flipa_review_nudge';  // user meta: 'done' = never show, 'later' = snoozed
	const META_UNTIL  = 'flipa_review_until';   // user meta: snooze-until timestamp

	public static function init() {
		add_action( 'admin_init',    array( __CLASS__, 'record_install' ) );
		add_action( 'admin_init',    array( __CLASS__, 'handle_action' ) );
		add_action( 'admin_notices', array( __CLASS__, 'maybe_render' ) );
	}

	/** Stamp the first-seen time once, so we can wait MIN_DAYS before asking. */
	public static function record_install() {
		if ( ! get_option( self::OPT_INSTALL ) ) {
			add_option( self::OPT_INSTALL, time(), '', false );
		}
	}

	/** Should the notice be considered at all for this user/build? */
	protected static function eligible() {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return false;
		}
		// Never nag paying customers (Pro) or the unlocked marketplace build.
		if ( function_exists( 'flipa_fs' ) && flipa_fs()->is_paying() ) {
			return false;
		}
		// Only on Flipa's own admin screens.
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || empty( $screen->post_type ) || FLIPA_CPT !== $screen->post_type ) {
			return false;
		}
		// Per-user state.
		$state = get_user_meta( get_current_user_id(), self::META_STATE, true );
		if ( 'done' === $state ) {
			return false;
		}
		if ( 'later' === $state ) {
			$until = (int) get_user_meta( get_current_user_id(), self::META_UNTIL, true );
			if ( $until > time() ) {
				return false;
			}
		}
		// Old enough?
		$installed = (int) get_option( self::OPT_INSTALL );
		if ( $installed && ( time() - $installed ) < ( self::MIN_DAYS * DAY_IN_SECONDS ) ) {
			return false;
		}
		// Has the user actually created a flipbook? (positive signal)
		$counts = wp_count_posts( FLIPA_CPT );
		$made   = isset( $counts->publish ) ? (int) $counts->publish : 0;
		if ( $made < 1 ) {
			return false;
		}
		return true;
	}

	public static function maybe_render() {
		if ( ! self::eligible() ) {
			return;
		}

		$review = self::REVIEW_URL;            // opens the wp.org review page in a new tab
		$later  = self::action_url( 'later' ); // snooze
		$did    = self::action_url( 'done' );  // never show again

		echo '<div class="notice notice-info is-dismissible" style="border-left-color:#6C5CE7">';
		echo '<p style="font-size:13px;line-height:1.5">';
		echo '<strong>' . esc_html__( 'Enjoying Flipa?', 'flipa-pdf-flipbook' ) . '</strong> ';
		echo esc_html__( "You've built a flipbook — a 30-second review would help others discover the plugin.", 'flipa-pdf-flipbook' );
		echo ' &#128153;</p><p>';
		printf(
			'<a href="%s" target="_blank" rel="noopener" class="button button-primary">%s</a> ',
			esc_url( $review ),
			esc_html__( 'Leave a review ★', 'flipa-pdf-flipbook' )
		);
		printf(
			'<a href="%s" class="button">%s</a> ',
			esc_url( $later ),
			esc_html__( 'Maybe later', 'flipa-pdf-flipbook' )
		);
		printf(
			'<a href="%s" class="button-link" style="margin-left:6px">%s</a>',
			esc_url( $did ),
			esc_html__( 'I already did', 'flipa-pdf-flipbook' )
		);
		echo '</p></div>';
	}

	/** Build a nonce-protected self-link that records the chosen action (later/done). */
	protected static function action_url( $do ) {
		$base = add_query_arg(
			array(
				'flipa_review'        => $do,
				'_wpnonce'            => wp_create_nonce( 'flipa_review_' . $do ),
			),
			admin_url( 'edit.php?post_type=' . FLIPA_CPT )
		);
		return $base;
	}

	/** Apply a click: set state, then (for review) bounce to wp.org. */
	public static function handle_action() {
		if ( empty( $_GET['flipa_review'] ) ) {
			return;
		}
		$do = sanitize_key( wp_unslash( $_GET['flipa_review'] ) );
		if ( ! in_array( $do, array( 'done', 'later' ), true ) ) {
			return;
		}
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'flipa_review_' . $do ) ) {
			return;
		}
		$uid = get_current_user_id();
		if ( 'later' === $do ) {
			update_user_meta( $uid, self::META_STATE, 'later' );
			update_user_meta( $uid, self::META_UNTIL, time() + ( self::SNOOZE_DAYS * DAY_IN_SECONDS ) );
		} else {
			update_user_meta( $uid, self::META_STATE, 'done' );
		}
		wp_safe_redirect( admin_url( 'edit.php?post_type=' . FLIPA_CPT ) );
		exit;
	}
}
