<?php

namespace RecastPaywall\Frontend;

use RecastPaywall\Services\EntitlementService;

/**
 * Themeable paywall renderer
 */
class PaywallRenderer {
    /**
     * Entitlement service
     */
    private EntitlementService $entitlementService;

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

    /**
     * Render post-level paywall (Medium.com style)
     */
    public function renderPostPaywall(int $postId, string $summary = ''): string {
        $post = get_post($postId);
        if (!$post) {
            return $this->renderErrorPaywall();
        }

        $inventoryData = $this->getInventoryData($postId);
        $userState = $this->getUserState();
        
        // Allow theme override via filter
        $html = apply_filters('recast_paywall_post_html', '', $postId, $inventoryData, $userState, $summary);
        if (!empty($html)) {
            return $html;
        }

        // Try to load template file (allows theme override)
        $template = $this->locateTemplate('paywall-post.php');
        if ($template) {
            ob_start();
            include $template;
            return ob_get_clean();
        }

        return $this->renderDefaultPostPaywall($post, $inventoryData, $userState, $summary);
    }

    /**
     * Render block-level paywall (streamlined)
     */
    public function renderBlockPaywall(int $postId, string $summary = ''): string {
        $post = get_post($postId);
        if (!$post) {
            return $this->renderErrorPaywall();
        }

        $inventoryData = $this->getInventoryData($postId);
        $userState = $this->getUserState();
        
        // Allow theme override via filter
        $html = apply_filters('recast_paywall_block_html', '', $postId, $inventoryData, $userState, $summary);
        if (!empty($html)) {
            return $html;
        }

        // Try to load template file (allows theme override)
        $template = $this->locateTemplate('paywall-block.php');
        if ($template) {
            ob_start();
            include $template;
            return ob_get_clean();
        }

        return $this->renderDefaultBlockPaywall($post, $inventoryData, $userState, $summary);
    }

    /**
     * Get inventory data for the post
     */
    private function getInventoryData(int $postId): array {
        $itemId = get_post_meta($postId, '_recast_inventory_item_id', true);
        $price = get_post_meta($postId, '_recast_price', true);
        $status = get_post_meta($postId, '_recast_status', true);
        
        return [
            'item_id' => $itemId,
            'price' => $price,
            'status' => $status,
            'currency' => 'USD', // Default, could be made configurable
        ];
    }

    /**
     * Get current user state
     */
    private function getUserState(): array {
        $user = wp_get_current_user();
        
        return [
            'is_logged_in' => is_user_logged_in(),
            'user_id' => get_current_user_id(),
            'user_email' => $user->user_email ?? '',
            'user_name' => $user->display_name ?? '',
        ];
    }

    /**
     * Render default post-level paywall (Medium.com style)
     */
    private function renderDefaultPostPaywall(\WP_Post $post, array $inventoryData, array $userState, string $summary): string {
        $price = $inventoryData['price'];
        $currency = $inventoryData['currency'];
        $status = $inventoryData['status'];
        
        $priceDisplay = $price ? sprintf('%s', number_format($price)) : 'Free';
        $statusDisplay = $this->getStatusDisplay($status);
        
        ob_start();
        ?>
        <div class="recast-paywall-post" data-post-id="<?php echo esc_attr($post->ID); ?>">
            <!-- Faded overlay -->
            <div class="recast-paywall-overlay"></div>
            
            <!-- Content preview -->
            <div class="recast-paywall-content">
                <div class="recast-paywall-summary">
                    <?php 
                    // Always show excerpt for paywalled posts
                    $excerpt = get_the_excerpt($post->ID);
                    echo wp_kses_post($excerpt ? wpautop($excerpt) : '<p>' . esc_html__('This content is protected. Purchase to view.', 'recast-paywall') . '</p>');
                    ?>
                </div>
                
                <!-- Paywall wall -->
                <div class="recast-paywall-wall">
                    <div class="recast-paywall-wall-content">
                        <div class="recast-paywall-logo">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>
                            </svg>
                            <span>Premium Content</span>
                        </div>
                        
                        <h2 class="recast-paywall-title"><?php echo esc_html($post->post_title); ?></h2>
                        
                        <div class="recast-paywall-pricing">
                            <div class="recast-paywall-price">
                                <?php echo esc_html($priceDisplay); ?>
                                <svg xmlns="http://www.w3.org/2000/svg" width="0.6em" height="0.6em" viewBox="0 0 21 22" role="img" class="" aria-hidden="true"><path fill="currentColor" fill-rule="nonzero" d="M0 12.497v9.168c0 .185.15.335.337.335H11.63c.09 0 .176-.036.239-.098l9.07-8.975a.167.167 0 0 0-.12-.285h-5.342a.168.168 0 0 0-.168.168v3.76a.168.168 0 0 1-.168.168H6.81a.168.168 0 0 1-.169-.167V6.663c0-.093.076-.168.169-.168h8.272a.17.17 0 0 1 .17.169v3.09c0 .093.075.168.168.168h5.413A.166.166 0 0 0 21 9.756V.166A.166.166 0 0 0 20.833 0h-8.392a.338.338 0 0 0-.237.097L.258 11.881a.865.865 0 0 0-.258.616"></path></svg>
                            </div>
                            <?php if ($statusDisplay): ?>
                                <div class="recast-paywall-status"><?php echo esc_html($statusDisplay); ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="recast-paywall-actions">
                            <?php if (!$userState['is_logged_in']): ?>
                                <div class="recast-paywall-login-prompt">
                                    <p>Please log in to purchase this content</p>
                                    <a href="<?php echo esc_url(wp_login_url(get_permalink($post->ID))); ?>" class="recast-paywall-button recast-paywall-button-primary">
                                        Log In
                                    </a>
                                </div>
                            <?php else: ?>
                                <div class="recast-paywall-purchase">
                                    <button class="recast-paywall-button recast-paywall-button-primary" onclick="recastPurchaseContent(<?php echo esc_js($post->ID); ?>, event)">
                                        Purchase for <?php echo esc_html($priceDisplay); ?>
                                        <svg xmlns="http://www.w3.org/2000/svg" width="0.6em" height="0.6em" viewBox="0 0 21 22" role="img" class="" aria-hidden="true"><path fill="currentColor" fill-rule="nonzero" d="M0 12.497v9.168c0 .185.15.335.337.335H11.63c.09 0 .176-.036.239-.098l9.07-8.975a.167.167 0 0 0-.12-.285h-5.342a.168.168 0 0 0-.168.168v3.76a.168.168 0 0 1-.168.168H6.81a.168.168 0 0 1-.169-.167V6.663c0-.093.076-.168.169-.168h8.272a.17.17 0 0 1 .17.169v3.09c0 .093.075.168.168.168h5.413A.166.166 0 0 0 21 9.756V.166A.166.166 0 0 0 20.833 0h-8.392a.338.338 0 0 0-.237.097L.258 11.881a.865.865 0 0 0-.258.616"></path></svg>
                                    </button>
                                    <p class="recast-paywall-note">One-time purchase • Lifetime access</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render default block-level paywall (streamlined)
     */
    private function renderDefaultBlockPaywall(\WP_Post $post, array $inventoryData, array $userState, string $summary): string {
        $price = $inventoryData['price'];
        $currency = $inventoryData['currency'];
        
        $priceDisplay = $price ? sprintf('%s', number_format($price)) : 'Free';
        
        ob_start();
        ?>
        <div class="recast-paywall-block" data-post-id="<?php echo esc_attr($post->ID); ?>">
            <div class="recast-paywall-block-content">
                <div class="recast-paywall-block-summary">
                    <?php echo wp_kses_post($summary ?: $this->getPostSummary($post->ID)); ?>
                </div>
                
                <div class="recast-paywall-block-cta">
                    <div class="recast-paywall-block-pricing">
                        <span class="recast-paywall-block-price">
                            <?php echo esc_html($priceDisplay); ?>
                        </span>
                    </div>
                    
                    <?php if (!$userState['is_logged_in']): ?>
                        <a href="<?php echo esc_url(wp_login_url(get_permalink($post->ID))); ?>" class="recast-paywall-block-button">
                            Log In to Purchase
                        </a>
                    <?php else: ?>
                        <button class="recast-paywall-block-button" onclick="recastPurchaseContent(<?php echo esc_js($post->ID); ?>, event)">
                            Purchase for <?php echo esc_html($priceDisplay); ?>
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render error paywall
     */
    private function renderErrorPaywall(): string {
        return '<div class="recast-paywall-error"><p>Content not available.</p></div>';
    }

    /**
     * Get post summary (always uses excerpt)
     */
    public function getPostSummary(int $postId): string {
        // Always use the post excerpt
        $excerpt = get_the_excerpt($postId);
        
        if (!empty($excerpt)) {
            return wpautop($excerpt);
        }

        // Get from database if not in loop
        $post = get_post($postId);
        if ($post && !empty($post->post_excerpt)) {
            return wpautop($post->post_excerpt);
        }

        // If no excerpt set, return a default message
        return '<p>' . esc_html__('This content is protected. Purchase to view.', 'recast-paywall') . '</p>';
    }

    /**
     * Get status display text
     */
    private function getStatusDisplay(?string $status): string {
        switch ($status) {
            case 'PRESALE':
                return 'Pre-sale available';
            case 'PURCHASEABLE':
                return 'Available now';
            case 'UNPURCHASEABLE':
                return 'Coming soon';
            default:
                return '';
        }
    }

    /**
     * Locate a template file following WordPress template hierarchy
     * 
     * Searches in:
     * 1. Child theme: wp-content/themes/child-theme/recast-paywall/
     * 2. Parent theme: wp-content/themes/parent-theme/recast-paywall/
     * 3. Plugin: wp-content/plugins/recast-paywall/templates/
     * 
     * @param string $template_name Template filename (e.g., 'paywall-post.php')
     * @return string|false Full path to template or false if not found
     */
    private function locateTemplate(string $template_name) {
        // Allow themes to filter the template locations
        $locations = apply_filters('recast_paywall_template_locations', [
            trailingslashit(get_stylesheet_directory()) . 'recast-paywall/',
            trailingslashit(get_template_directory()) . 'recast-paywall/',
            RECAST_PAYWALL_PLUGIN_DIR . 'templates/',
        ], $template_name);

        foreach ($locations as $location) {
            $file = $location . $template_name;
            if (file_exists($file)) {
                return apply_filters('recast_paywall_template_path', $file, $template_name, $location);
            }
        }

        return false;
    }

    /**
     * Load a template part
     * 
     * Makes variables available to the template:
     * - $post: WP_Post object
     * - $postId: Post ID
     * - $inventoryData: Inventory data array
     * - $userState: User state array
     * - $summary: Content summary
     * - $renderer: This PaywallRenderer instance (for helper methods)
     * 
     * @param string $slug Template slug (e.g., 'paywall', 'pricing')
     * @param string|null $name Optional. Template name (e.g., 'post', 'block')
     * @param array $args Optional. Additional variables to pass to template
     */
    public function getTemplatePart(string $slug, ?string $name = null, array $args = []): void {
        $templates = [];
        
        if ($name) {
            $templates[] = "{$slug}-{$name}.php";
        }
        $templates[] = "{$slug}.php";

        // Extract args to make them available in template
        extract($args); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract
        
        foreach ($templates as $template_name) {
            $template = $this->locateTemplate($template_name);
            if ($template) {
                include $template;
                return;
            }
        }
    }
}
