<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Front-end paywall presentation: blurred preview + CTA panel.
 */
class BSPP_Paywall_Overlay {
    public const STYLE_HANDLE = 'bspp-paywall-overlay';

    /**
     * Whether the current singular post is locked for the visitor.
     */
    public static function is_post_locked_for_visitor( $post_id ) {
        $post_id = (int) $post_id;
        if ( $post_id <= 0 ) {
            return false;
        }
        $paywall = new BSPP_Paywall_Engine();
        return !$paywall->is_post_unlocked( $post_id, get_current_user_id() );
    }

    /**
     * Register and enqueue overlay CSS (call from wp_enqueue_scripts).
     */
    public static function enqueue_assets() {
        if ( !defined( 'BSPP_PLUGIN_URL' ) ) {
            return;
        }
        wp_register_style(
            self::STYLE_HANDLE,
            BSPP_PLUGIN_URL . 'public/css/paywall-overlay.css',
            [],
            BSPP_VERSION
        );
        wp_enqueue_style( self::STYLE_HANDLE );
    }

    /**
     * HTML for locked view: blurred preview + gate UI.
     *
     * @param int    $post_id Post ID.
     * @param string $full_content Original post content (HTML).
     * @param array  $simulation_context Optional Tools preview simulation.
     */
    public static function render( $post_id, $full_content, $simulation_context = [] ) {
        $post_id = (int) $post_id;
        if ( $post_id <= 0 ) {
            return '';
        }
        self::enqueue_assets();
        $preview_text = self::build_locked_preview_plain_text( $full_content );
        $settings = new BSPP_Settings_Repository();
        $d = BSPP_Settings_Repository::defaults();
        $enable_subscription = (int) $settings->get( 'enable_subscription', $d['enable_subscription'] );
        $subscription_price = $settings->get( 'subscription_price_monthly', $d['subscription_price_monthly'] );
        $annual_subscription_price = $settings->get( 'subscription_price_annual', $d['subscription_price_annual'] );
        // Free-build defaults: no Pro CTAs.
        $enable_tip_unlock = 0;
        $enable_article_unlock = 0;
        $unlock_price = 0;
        $default_tip_amount = 0;
        $minimum_tip_amount = 0;
        $bspp_premium = false;
        $show_free_indicator = false;
        $free_indicator_text = '';
        $show_free_unlock_action = false;
        $show_anonymous_prompt = false;
        $anonymous_prompt_text = '';
        $free_article_limit = 0;
        $user_id = get_current_user_id();
        $is_logged_in = $user_id > 0;
        $is_paid_member = false;
        $simulation = ( is_array( $simulation_context ) ? $simulation_context : [] );
        $has_simulation = !empty( $simulation );
        if ( $has_simulation && isset( $simulation['reader_state'] ) ) {
            $reader_state = sanitize_key( (string) $simulation['reader_state'] );
            if ( !in_array( $reader_state, ['anonymous', 'free', 'paid'], true ) ) {
                $reader_state = 'anonymous';
            }
            $is_logged_in = $reader_state !== 'anonymous';
            $is_paid_member = $reader_state === 'paid';
            if ( !$is_logged_in ) {
                $user_id = 0;
            }
        } elseif ( $is_logged_in ) {
            $membership_repo = new BSPP_Membership_Repository();
            $is_paid_member = $membership_repo->is_active( $user_id );
        }
        $heading_id = 'sp-paywall-heading-' . $post_id;
        $status_id = 'sp-paywall-status-' . $post_id;
        $magic_login_url = add_query_arg( 'bspp_magic_login', '1', get_permalink( $post_id ) );
        ob_start();
        $template = BSPP_PLUGIN_PATH . 'templates/paywall-overlay.php';
        if ( is_readable( $template ) ) {
            include $template;
        }
        return (string) ob_get_clean();
    }

    /**
     * Lightweight banner for unlocked-state free quota messaging (shown above article content).
     */
    public static function render_unlocked_free_indicator_banner( $post_id ) {
        return '';
    }

    /**
     * Plain text for the blurred teaser: enough words to read as several lines after blur.
     */
    private static function build_locked_preview_plain_text( $html_content ) {
        $html_content = (string) $html_content;
        if ( $html_content === '' ) {
            return '';
        }
        if ( function_exists( 'do_shortcode' ) ) {
            $html_content = do_shortcode( $html_content );
        }
        $plain = wp_strip_all_tags( $html_content, true );
        $plain = html_entity_decode( $plain, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
        $plain = preg_replace( "/[\r\n]+/", "\n", trim( $plain ) );
        $first_block = $plain;
        if ( strpos( $plain, "\n\n" ) !== false ) {
            $parts = explode( "\n\n", $plain, 2 );
            $first_block = trim( (string) ($parts[0] ?? '') );
        }
        $first_block = preg_replace( '/\\s+/u', ' ', $first_block );
        $full_one_line = preg_replace( '/\\s+/u', ' ', $plain );
        $excerpt = $first_block;
        if ( function_exists( 'mb_strlen' ) && mb_strlen( $excerpt ) < 220 && $full_one_line !== '' ) {
            $excerpt = wp_trim_words( $full_one_line, 130, '…' );
        } elseif ( strlen( $excerpt ) < 220 && $full_one_line !== '' ) {
            $excerpt = wp_trim_words( $full_one_line, 130, '…' );
        }
        return $excerpt;
    }

}
