<?php

namespace RecastPaywall\Frontend;

use RecastPaywall\Services\EntitlementService;

/**
 * Block-level content gating
 */
class BlockGating {
    /**
     * Entitlement service
     */
    private EntitlementService $entitlementService;

    /**
     * Paywall renderer
     */
    private PaywallRenderer $paywallRenderer;

    /**
     * Constructor
     */
    public function __construct(EntitlementService $entitlementService, PaywallRenderer $paywallRenderer) {
        $this->entitlementService = $entitlementService;
        $this->paywallRenderer = $paywallRenderer;
    }

    /**
     * Initialize hooks
     */
    public function init(): void {
        // Gate selected blocks via toolbar toggle when in block mode
        // Use lower priority (higher number) to ensure post-level filtering happens first
        add_filter('render_block', [$this, 'filterRenderedBlock'], 20, 2);
    }

    /**
     * Gate arbitrary blocks marked with recastGated when in block gating mode
     */
    public function filterRenderedBlock(string $blockContent, array $block): string {
        static $processingBlocks = [];
        
        // Prevent infinite loops
        $blockKey = $block['blockName'] ?? 'unknown';
        if (isset($processingBlocks[$blockKey])) {
            return $blockContent;
        }
        
        if (!is_singular()) {
            return $blockContent;
        }

        $postId = get_the_ID();
        if (!$postId) {
            return $blockContent;
        }

        $mode = get_post_meta($postId, '_recast_gating_mode', true) ?: 'post';
        if ($mode !== 'block') {
            return $blockContent;
        }

        // Skip our legacy dedicated block if present
        if (!empty($block['blockName']) && $block['blockName'] === 'recast-paywall/paywall-section') {
            return $blockContent;
        }

        $attrs = $block['attrs'] ?? [];
        if (empty($attrs['recastGated'])) {
            return $blockContent;
        }
        
        // Mark this block as being processed
        $processingBlocks[$blockKey] = true;
        
        try {
            // This block is marked for gating, check entitlement
            $userId = get_current_user_id();
            if (empty($userId)) {
                return $this->paywallRenderer->renderBlockPaywall($postId);
            }

            $isEntitled = $this->entitlementService->isEntitled($postId, $userId);
            
            // Block gating decision made
            
            if ($isEntitled) {
                return $blockContent;
            }

            // User is not entitled, show paywall
            return $this->paywallRenderer->renderBlockPaywall($postId);
        } finally {
            // Always clear the processing flag
            unset($processingBlocks[$blockKey]);
        }
    }


}
