<?php

namespace RecastPaywall\Blocks;

use RecastPaywall\Services\EntitlementService;
use RecastPaywall\Frontend\ContentGating;

/**
 * Gutenberg block for paywall sections
 */
class PaywallBlock {
    /**
     * Entitlement service
     */
    private EntitlementService $entitlementService;

    /**
     * Content gating service
     */
    private ContentGating $contentGating;

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

    /**
     * Register block
     */
    public function registerBlock(): void {
        // Register the block with block.json or inline configuration
        register_block_type('recast-paywall/paywall-section', [
            'render_callback' => [$this, 'renderBlock'],
            'attributes' => [
                'postId' => [
                    'type' => 'number',
                    'default' => 0,
                ],
            ],
            'supports' => [
                'html' => false,
                'align' => true,
            ],
        ]);
    }

    /**
     * Render block
     */
    public function renderBlock(array $attributes, string $content): string {
        // Check memory usage and prevent exhaustion
        if (function_exists('memory_get_usage') && memory_get_usage() > 200 * 1024 * 1024) { // 200MB limit
            return $content;
        }
        
        $postId = $attributes['postId'] ?? get_the_ID();
        
        if (!$postId) {
            return $content;
        }

        // Check if user is entitled
        $userId = get_current_user_id();
        if ($this->entitlementService->isEntitled($postId, $userId)) {
            return $content;
        }

        // User is not entitled, show paywall
        return sprintf(
            '<div class="recast-paywall-section" data-post-id="%d">
                <div class="recast-paywall-section-content">%s</div>
                <div class="recast-paywall-section-cta">%s</div>
            </div>',
            $postId,
            $this->contentGating->getPostSummary($postId),
            $this->contentGating->getPaywallHtml($postId)
        );
    }
}
