<?php
/**
 * Functions to handle block editor extensions for PinnerPress
 *
 * @link       https://pinnerpress.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */

if (!defined('WPINC')) {
    die;
}

/**
 * Apply PinnerPress attributes to image blocks in the rendered content
 * 
 * @since 0.1.0
 * @param string $block_content The block content about to be rendered on the front end.
 * @param array  $block         The full block, including name and attributes.
 * @return string               The modified block content.
 */
function pinnerpress_process_image_block($block_content, $block) {
    // Only target image blocks
    if ($block['blockName'] !== 'core/image') {
        return $block_content;
    }
    
    // Check if block has any custom Pinterest attributes
    $attributes = $block['attrs'];
    $has_pinterest_attributes = false;
    
    // Check for custom Pinterest attributes
    $pinterest_attrs = [];
    
    if (!empty($attributes['pinterestTitle'])) {
        $pinterest_attrs['data-pin-title'] = esc_attr($attributes['pinterestTitle']);
        $has_pinterest_attributes = true;
    }
    
    if (!empty($attributes['pinterestText'])) {
        $pinterest_attrs['data-pin-description'] = esc_attr($attributes['pinterestText']);
        $has_pinterest_attributes = true;
    }
    
    if (!empty($attributes['pinterestRepinId'])) {
        $pinterest_attrs['data-pin-id'] = esc_attr($attributes['pinterestRepinId']);
        $has_pinterest_attributes = true;
    }
    
    // Handle disable pinning attribute
    if (isset($attributes['pinterestDisablePinning']) && $attributes['pinterestDisablePinning']) {
        $pinterest_attrs['data-pin-nopin'] = 'true';
        $has_pinterest_attributes = true;
    }
    
    // If no Pinterest attributes, return the original content
    if (!$has_pinterest_attributes) {
        return $block_content;
    }
    
    // Add the attributes to the img tag
    $dom = new DOMDocument();
    
    // Suppress errors from malformed HTML
    $libxml_previous_state = libxml_use_internal_errors(true);
    
    // Load the block content
    @$dom->loadHTML(mb_convert_encoding($block_content, 'HTML-ENTITIES', 'UTF-8'));
    
    // Find the image tag
    $images = $dom->getElementsByTagName('img');
    
    if ($images->length > 0) {
        $img = $images->item(0);
        
        // Apply Pinterest attributes
        foreach ($pinterest_attrs as $attr => $value) {
            $img->setAttribute($attr, $value);
        }
        
        // If pinning is disabled, also add a class to hide the pin button via CSS
        if (isset($pinterest_attrs['data-pin-nopin'])) {
            $img_parent = $img->parentNode;
            if ($img_parent->nodeName === 'figure' || $img_parent->nodeName === 'div') {
                $existing_class = $img_parent->getAttribute('class');
                $img_parent->setAttribute('class', $existing_class . ' pinnerpress-pinning-disabled');
            }
        }
        
        // Save the modified content
        $body = $dom->getElementsByTagName('body')->item(0);
        $modified_content = '';
        
        // Get the content of the body tag
        foreach ($body->childNodes as $child) {
            $modified_content .= $dom->saveHTML($child);
        }
        
        // Restore the block content with our modifications
        $block_content = $modified_content;
    }
    
    // Restore LibXML error handling
    libxml_use_internal_errors($libxml_previous_state);
    
    return $block_content;
}

/**
 * Register block extensions for premium users
 *
 * @since    0.1.0
 */
function pinnerpress_register_block_extensions() {
    // These extensions are premium features
    if (!pinnerpress_is_premium()) {
        return;
    }

    // Hook the image block processor to the render_block filter
    add_filter('render_block', 'pinnerpress_process_image_block', 10, 2);

    // Add a filter hook for the pin button options
    add_filter('pinnerpress_pin_button_options', 'pinnerpress_modify_pin_button_options', 10, 3);
}
add_action('init', 'pinnerpress_register_block_extensions');

/**
 * Process the post content to respect Pinterest attributes when adding Pin buttons
 * 
 * @since 0.1.0
 * @param array  $pin_button_options The options used to render the pin button
 * @param string $image_url The URL of the image
 * @param object $img The image DOM element
 * @return array The modified pin button options
 */
function pinnerpress_modify_pin_button_options($pin_button_options, $image_url, $img) {
    // Check for custom Pinterest attributes
    $pinterest_title = $img->getAttribute('data-pin-title');
    $pinterest_text = $img->getAttribute('data-pin-description');
    $pinterest_repin_id = $img->getAttribute('data-pin-id');
    $disable_pinning = $img->getAttribute('data-pin-nopin');
    
    // Add custom attributes to the pin button options
    if (!empty($pinterest_title)) {
        $pin_button_options['pinterest_title'] = $pinterest_title;
    }
    
    if (!empty($pinterest_text)) {
        $pin_button_options['pinterest_text'] = $pinterest_text;
    }
    
    if (!empty($pinterest_repin_id)) {
        $pin_button_options['pinterest_repin_id'] = $pinterest_repin_id;
    }
    
    if ($disable_pinning === 'true') {
        $pin_button_options['disable_pinning'] = true;
    }
    
    return $pin_button_options;
} 