<?php
namespace AIFI;

/**
 * Polite, dismissible request asking happy users to leave a wp.org review.
 * Triggers only after the user has had the plugin installed for at least
 * 7 days AND has successfully generated at least 3 images.
 *
 * @package AIFI
 */
class Review_Request {

    const INSTALL_DATE_OPTION = 'aifi_install_date';
    const COUNT_OPTION        = 'aifi_generation_count';
    const STATE_OPTION        = 'aifi_review_state';

    const MIN_DAYS_INSTALLED  = 7;
    const MIN_GENERATIONS     = 3;
    const RESNOOZE_DAYS       = 30;

    const REVIEW_URL = 'https://wordpress.org/support/plugin/ai-featured-image-generator/reviews/?filter=5#new-post';

    /**
     * Settings instance, used to look up enabled post types for the meta box
     * gate.
     *
     * @var Settings
     */
    private $settings;

    /**
     * @param Settings $settings
     */
    public function __construct($settings) {
        $this->settings = $settings;

        add_action('admin_init', array($this, 'maybe_set_install_date'));
        add_action('aifi_after_generate', array($this, 'increment_count'), 10, 2);
        add_action('aifi_after_generate_inline', array($this, 'increment_count'), 10, 2);
        add_action('admin_notices', array($this, 'render_notice'));
        add_action('rest_api_init', array($this, 'register_route'));
    }

    /**
     * Stamp the install date the first time we see this admin user. For users
     * upgrading from an older version, this becomes the upgrade date — the
     * 7-day clock simply starts then.
     */
    public function maybe_set_install_date() {
        if (get_option(self::INSTALL_DATE_OPTION) === false) {
            update_option(self::INSTALL_DATE_OPTION, time());
        }
    }

    /**
     * Bumps the successful generation counter. Hooked to the existing
     * aifi_after_generate / aifi_after_generate_inline actions in Generator.
     *
     * @param int $attachment_id
     * @param int $post_id
     */
    public function increment_count($attachment_id, $post_id) {
        unset($attachment_id, $post_id);
        $count = (int) get_option(self::COUNT_OPTION, 0);
        update_option(self::COUNT_OPTION, $count + 1, false);
    }

    /**
     * Decide whether the notice should appear on the current screen.
     *
     * @return bool
     */
    private function should_display() {
        if (!current_user_can('manage_options')) {
            return false;
        }

        $state = get_option(self::STATE_OPTION, '');
        if ($state === 'done' || $state === 'never') {
            return false;
        }
        if (strpos((string) $state, 'dismissed:') === 0) {
            $ts = (int) substr($state, strlen('dismissed:'));
            if ($ts > 0 && (time() - $ts) < self::RESNOOZE_DAYS * DAY_IN_SECONDS) {
                return false;
            }
        }

        $install_date = (int) get_option(self::INSTALL_DATE_OPTION, 0);
        if ($install_date <= 0) {
            return false;
        }
        if ((time() - $install_date) < self::MIN_DAYS_INSTALLED * DAY_IN_SECONDS) {
            return false;
        }

        $count = (int) get_option(self::COUNT_OPTION, 0);
        if ($count < self::MIN_GENERATIONS) {
            return false;
        }

        return $this->is_aifi_screen();
    }

    /**
     * True if we're on an AIFIG-relevant admin screen — the settings page or
     * a post-edit screen for an enabled post type.
     *
     * @return bool
     */
    private function is_aifi_screen() {
        if (!function_exists('get_current_screen')) {
            return false;
        }
        $screen = get_current_screen();
        if (!$screen) {
            return false;
        }

        if ($screen->id === 'toplevel_page_ai-featured-image-generator') {
            return true;
        }

        if (in_array($screen->base, array('post'), true)) {
            $enabled = $this->settings->get_enabled_post_types();
            if (!empty($screen->post_type) && in_array($screen->post_type, $enabled, true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Render the review request notice.
     */
    public function render_notice() {
        if (!$this->should_display()) {
            return;
        }

        $nonce = wp_create_nonce('wp_rest');
        $rest  = esc_url_raw(rest_url('aifi/v1/review-state'));
        ?>
        <div class="notice aifi-review-notice" data-aifi-review data-rest="<?php echo esc_attr($rest); ?>" data-nonce="<?php echo esc_attr($nonce); ?>">
            <div class="aifi-review-notice-icon">
                <span class="dashicons dashicons-star-filled"></span>
            </div>
            <div class="aifi-review-notice-body">
                <p class="aifi-review-notice-title">
                    <strong><?php esc_html_e('Enjoying AI Featured Image?', 'ai-featured-image-generator'); ?></strong>
                </p>
                <p class="aifi-review-notice-text">
                    <?php esc_html_e('We are a small team and a kind 5-star review on WordPress.org would mean a lot. It helps other users discover the plugin and motivates us to keep improving it. Thank you!', 'ai-featured-image-generator'); ?>
                </p>
                <p class="aifi-review-notice-actions">
                    <a href="<?php echo esc_url(self::REVIEW_URL); ?>" target="_blank" rel="noopener noreferrer" class="button button-primary" data-aifi-review-action="done">
                        <span class="dashicons dashicons-star-filled"></span>
                        <?php esc_html_e('Leave a review', 'ai-featured-image-generator'); ?>
                    </a>
                    <button type="button" class="button" data-aifi-review-action="dismissed">
                        <?php esc_html_e('Maybe later', 'ai-featured-image-generator'); ?>
                    </button>
                    <button type="button" class="button-link aifi-review-notice-never" data-aifi-review-action="never">
                        <?php esc_html_e("I've already left one — don't ask again", 'ai-featured-image-generator'); ?>
                    </button>
                </p>
            </div>
        </div>
        <?php
    }

    /**
     * Register the dismissal endpoint.
     */
    public function register_route() {
        register_rest_route('aifi/v1', '/review-state', array(
            'methods'             => 'POST',
            'callback'            => array($this, 'handle_state_change'),
            'permission_callback' => function() {
                return current_user_can('manage_options');
            },
            'args' => array(
                'state' => array(
                    'required'          => true,
                    'type'              => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ),
            ),
        ));
    }

    /**
     * Handle a state change request from the notice's JS.
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response|\WP_Error
     */
    public function handle_state_change($request) {
        $state = (string) $request->get_param('state');

        switch ($state) {
            case 'dismissed':
                update_option(self::STATE_OPTION, 'dismissed:' . time(), false);
                break;
            case 'done':
                update_option(self::STATE_OPTION, 'done', false);
                break;
            case 'never':
                update_option(self::STATE_OPTION, 'never', false);
                break;
            default:
                return new \WP_Error('aifi_invalid_state', __('Invalid state.', 'ai-featured-image-generator'), array('status' => 400));
        }

        return rest_ensure_response(array('ok' => true));
    }
}
