<?php
/**
 * Theme Integration Examples for Recast Paywall
 * 
 * This file shows how to customize the paywall HTML and styling
 * to match your theme's design.
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Example 1: Customize post-level paywall HTML (Post Gating Mode)
add_filter('recast_paywall_post_html', function($html, $postId, $inventoryData, $userState, $summary) {
    // Only customize if you want to override the default
    if (!empty($html)) {
        return $html;
    }
    
    // Your custom HTML here
    $price = $inventoryData['price'];
    $priceDisplay = $price ? sprintf('%s', number_format($price)) : 'Free';
    
    ob_start();
    ?>
    <div class="my-theme-paywall" data-post-id="<?php echo esc_attr($postId); ?>">
        <div class="my-theme-paywall-content">
            <div class="my-theme-paywall-summary">
                <?php echo wp_kses_post($summary); ?>
            </div>
            
            <div class="my-theme-paywall-wall">
                <h2>Premium Content</h2>
                <div class="my-theme-paywall-price"><?php echo esc_html($priceDisplay); ?></div>
                
                <?php if (!$userState['is_logged_in']): ?>
                    <a href="<?php echo esc_url(wp_login_url(get_permalink($postId))); ?>" class="my-theme-button">
                        Log In to Purchase
                    </a>
                <?php else: ?>
                    <button class="my-theme-button" onclick="recastPurchaseContent(<?php echo esc_js($postId); ?>)">
                        Purchase for <?php echo esc_html($priceDisplay); ?>
                        
                    </button>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}, 10, 5);

// Example 2: Customize block-level paywall HTML (Block Gating Mode)
add_filter('recast_paywall_block_html', function($html, $postId, $inventoryData, $userState, $summary) {
    // Only customize if you want to override the default
    if (!empty($html)) {
        return $html;
    }
    
    // Your custom HTML here
    $price = $inventoryData['price'];
    $priceDisplay = $price ? sprintf('%s', number_format($price)) : 'Free';
    
    ob_start();
    ?>
    <div class="my-theme-block-paywall" data-post-id="<?php echo esc_attr($postId); ?>">
        <div class="my-theme-block-summary">
            <?php echo wp_kses_post($summary); ?>
        </div>
        
        <div class="my-theme-block-cta">
            <span class="my-theme-block-price"><?php echo esc_html($priceDisplay); ?></span>
            
            <?php if (!$userState['is_logged_in']): ?>
                <a href="<?php echo esc_url(wp_login_url(get_permalink($postId))); ?>" class="my-theme-block-button">
                    Log In
                </a>
            <?php else: ?>
                <button class="my-theme-block-button" onclick="recastPurchaseContent(<?php echo esc_js($postId); ?>)">
                    Purchase
                </button>
            <?php endif; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}, 10, 5);

// Example 3: Add custom CSS for your theme using wp_add_inline_style
add_action('wp_enqueue_scripts', function() {
    $custom_css = "
    /* Custom paywall styles for your theme */
    .my-theme-paywall {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 12px;
        padding: 2rem;
        color: white;
        text-align: center;
        margin: 2rem 0;
    }
    
    .my-theme-paywall-summary {
        margin-bottom: 2rem;
        line-height: 1.6;
    }
    
    .my-theme-paywall-wall h2 {
        font-size: 2rem;
        margin-bottom: 1rem;
    }
    
    .my-theme-paywall-price {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 2rem;
    }
    
    .my-theme-button {
        display: inline-block;
        padding: 1rem 2rem;
        background: white;
        color: #667eea;
        border: none;
        border-radius: 8px;
        font-size: 1rem;
        font-weight: 600;
        text-decoration: none;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .my-theme-button:hover {
        background: #f8f9fa;
        transform: translateY(-2px);
    }
    
    .my-theme-block-paywall {
        background: #f8f9fa;
        border: 2px dashed #dee2e6;
        border-radius: 8px;
        padding: 1.5rem;
        margin: 1rem 0;
        text-align: center;
    }
    
    .my-theme-block-summary {
        margin-bottom: 1.5rem;
        line-height: 1.5;
        color: #6c757d;
    }
    
    .my-theme-block-cta {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 1rem;
    }
    
    .my-theme-block-price {
        font-size: 1.5rem;
        font-weight: bold;
        color: #495057;
    }
    
    .my-theme-block-button {
        display: inline-block;
        padding: 0.75rem 1.5rem;
        background: #667eea;
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 0.95rem;
        font-weight: 600;
        text-decoration: none;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .my-theme-block-button:hover {
        background: #5a6fd8;
        transform: translateY(-1px);
    }
    ";
    wp_add_inline_style('recast-paywall-styles', $custom_css);
});

// Example 4: Customize the purchase function using wp_add_inline_script
add_action('wp_enqueue_scripts', function() {
    $custom_js = "
    // Custom purchase function
    function recastPurchaseContent(postId) {
        // Show loading state
        const button = event.target;
        const originalText = button.textContent;
        button.textContent = 'Processing...';
        button.disabled = true;
        
        // Make purchase request
        fetch('/wp-json/recast-paywall/v1/purchase', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': recastPaywall.nonce
            },
            body: JSON.stringify({
                post_id: postId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Purchase successful, reload page to show content
                window.location.reload();
            } else {
                // Show error
                alert(data.message || 'Purchase failed. Please try again.');
                button.textContent = originalText;
                button.disabled = false;
            }
        })
        .catch(error => {
            console.error('Purchase error:', error);
            alert('Purchase failed. Please try again.');
            button.textContent = originalText;
            button.disabled = false;
        });
    }
    ";
    wp_add_inline_script('recast-paywall-frontend', $custom_js);
}, 20);

// Example 5: Add custom hooks for theme integration
add_action('recast_paywall_before_content', function($postId) {
    // Add content before the paywall
    echo '<div class="my-theme-paywall-intro">This is premium content from our partners.</div>';
});

add_action('recast_paywall_after_content', function($postId) {
    // Add content after the paywall
    echo '<div class="my-theme-paywall-footer">Thank you for supporting quality content.</div>';
});

// Example 6: Customize the summary length
add_filter('recast_paywall_summary_length', function($length) {
    // Set custom summary length for your theme
    return 150; // Show 150 words instead of default 100
});

// Example 7: Add custom user state data
add_filter('recast_paywall_user_state', function($userState, $postId) {
    // Add custom user state data
    $userState['user_role'] = wp_get_current_user()->roles[0] ?? '';
    $userState['user_registration_date'] = wp_get_current_user()->user_registered ?? '';
    
    return $userState;
}, 10, 2);

// Example 8: Customize inventory data
add_filter('recast_paywall_inventory_data', function($inventoryData, $postId) {
    // Add custom inventory data
    $inventoryData['author'] = get_the_author_meta('display_name', get_post_field('post_author', $postId));
    $inventoryData['category'] = get_the_category($postId)[0]->name ?? '';
    
    return $inventoryData;
}, 10, 2);

// Example 9: Detect and handle different gating modes using wp_add_inline_style
add_action('wp_enqueue_scripts', function() {
    if (is_singular()) {
        $postId = get_the_ID();
        $gatingMode = get_post_meta($postId, '_recast_gating_mode', true) ?: 'post';
        
        if ($gatingMode === 'block') {
            // Add custom styles for block gating mode
            $custom_css = "
            .my-theme-block-gating-mode .recast-paywall-block {
                border-left: 4px solid #667eea;
                background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            }
            ";
            wp_add_inline_style('recast-paywall-styles', $custom_css);
        } else {
            // Add custom styles for post gating mode
            $custom_css = "
            .my-theme-post-gating-mode .recast-paywall-post {
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
            }
            ";
            wp_add_inline_style('recast-paywall-styles', $custom_css);
        }
    }
}, 20);

// Example 10: Add custom JavaScript for toolbar integration using wp_add_inline_script
add_action('wp_enqueue_scripts', function() {
    $custom_js = "
    // Listen for block gating changes
    document.addEventListener('DOMContentLoaded', function() {
        // Add custom behavior for gated blocks
        const gatedBlocks = document.querySelectorAll('.recast-paywall-block');
        gatedBlocks.forEach(function(block) {
            // Add custom hover effects
            block.addEventListener('mouseenter', function() {
                this.style.transform = 'scale(1.02)';
            });
            
            block.addEventListener('mouseleave', function() {
                this.style.transform = 'scale(1)';
            });
        });
        
        // Add custom purchase tracking
        window.recastCustomPurchaseTracking = function(postId, blockId) {
            // Track which blocks are being purchased
            if (typeof gtag !== 'undefined') {
                gtag('event', 'block_purchase', {
                    'post_id': postId,
                    'block_id': blockId,
                    'gating_mode': 'block'
                });
            }
        };
    });
    ";
    wp_add_inline_script('recast-paywall-frontend', $custom_js);
}, 20);
