<?php
/**
 * Hidden Pinterest Images functionality
 *
 * @link       https://pinnerpress.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */

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

/**
 * Add hidden Pinterest images to the page content
 *
 * @since    0.1.0
 * @param    string    $content    The post content
 * @return   string                The modified content with hidden images
 */
function pinnerpress_add_hidden_images_to_content($content) {
    // Only add hidden images on singular posts/pages
    if (!is_singular()) {
        return $content;
    }
    
    // Get the current post ID
    $post_id = get_the_ID();
    if (!$post_id) {
        return $content;
    }
    
    // Get hidden images for this post
    $hidden_images = get_post_meta($post_id, '_pinnerpress_hidden_images', true);
    
    // If no hidden images, return original content
    if (empty($hidden_images) || !is_array($hidden_images)) {
        return $content;
    }
    
    // Generate hidden images HTML
    $hidden_images_html = pinnerpress_generate_hidden_images_html($hidden_images);
    
    // Add hidden images to the end of the content
    return $content . $hidden_images_html;
}

/**
 * Generate HTML for hidden Pinterest images
 *
 * @since    0.1.0
 * @param    array    $hidden_images    Array of hidden image data
 * @return   string                     HTML for hidden images
 */
function pinnerpress_generate_hidden_images_html($hidden_images) {
    if (empty($hidden_images) || !is_array($hidden_images)) {
        return '';
    }
    
    $html = '';
    
    // Start hidden images container
    $html .= '<div class="pinnerpress-hidden-images" style="display: none; visibility: hidden; position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;">';
    
    foreach ($hidden_images as $index => $image) {
        if (empty($image['url'])) {
            continue;
        }
        
        $url = esc_url($image['url']);
        $page_title = get_the_title();
        $page_url = get_permalink();
        
        // Generate Pinterest sharing URL for this image
        $pin_url = 'https://www.pinterest.com/pin/create/button/' .
                   '?url=' . urlencode($page_url) .
                   '&media=' . urlencode($url) .
                   '&description=' . urlencode($page_title);
        
        // Create hidden image element with Pinterest data attributes
        // Check if this is a WordPress attachment (cache result to avoid expensive LIKE query per image)
        static $url_to_id_cache = array();
        if (isset($url_to_id_cache[$url])) {
            $attachment_id = $url_to_id_cache[$url];
        } else {
            $attachment_id = attachment_url_to_postid($url);
            $url_to_id_cache[$url] = $attachment_id;
        }
        
        if ($attachment_id) {
            // Use WordPress function for attachment images
            $img_html = wp_get_attachment_image(
                $attachment_id,
                'full',
                false,
                array(
                    'data-pin-url' => esc_url($page_url),
                    'data-pin-media' => $url,
                    'data-pin-description' => esc_attr($page_title),
                    'data-pin-do' => 'buttonPin',
                    'data-pin-custom' => 'true',
                    'class' => 'pinnerpress-hidden-image',
                    'loading' => 'lazy'
                )
            );
            // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedImage -- Image generated by wp_get_attachment_image()
            $html .= $img_html;
        } else {
            // For external images, we need to create the img tag manually
            // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedImage -- External image URL, not a WordPress attachment
            $html .= sprintf(
                '<img src="%s" alt="%s" data-pin-url="%s" data-pin-media="%s" data-pin-description="%s" data-pin-do="buttonPin" data-pin-custom="true" class="pinnerpress-hidden-image" loading="lazy" />',
                $url,
                esc_attr($page_title),
                esc_url($page_url),
                $url,
                esc_attr($page_title)
            );
        }
    }
    
    // Close hidden images container
    $html .= '</div>';
    
    return $html;
}

/**
 * Add hidden images to wp_head for better Pinterest discovery
 *
 * @since    0.1.0
 */
function pinnerpress_add_hidden_images_to_head() {
    // Only add on singular posts/pages
    if (!is_singular()) {
        return;
    }
    
    // Get the current post ID
    $post_id = get_the_ID();
    if (!$post_id) {
        return;
    }
    
    // Get hidden images for this post
    $hidden_images = get_post_meta($post_id, '_pinnerpress_hidden_images', true);
    
    // If no hidden images, return
    if (empty($hidden_images) || !is_array($hidden_images)) {
        return;
    }
    
    // Add meta tags for Pinterest
    echo "<!-- PinnerPress Hidden Images -->\n";
    
    $page_title = get_the_title();
    
    foreach ($hidden_images as $index => $image) {
        if (empty($image['url'])) {
            continue;
        }
        
        $url = esc_url($image['url']);
        
        // Add Open Graph image meta tag
        echo '<meta property="og:image" content="' . esc_url($url) . '" />' . "\n";
        
        // Add Pinterest-specific meta tag with page title as description
        echo '<meta name="pinterest-description" content="' . esc_attr($page_title) . '" />' . "\n";
    }
    
    echo "<!-- /PinnerPress Hidden Images -->\n";
}

/**
 * Initialize hidden images functionality
 *
 * @since    0.1.0
 */
function pinnerpress_init_hidden_images() {
    // Add hidden images to content
    add_filter('the_content', 'pinnerpress_add_hidden_images_to_content', 20);
    
    // Add hidden images meta tags to head
    add_action('wp_head', 'pinnerpress_add_hidden_images_to_head', 5);
}

// Initialize the functionality
add_action('init', 'pinnerpress_init_hidden_images'); 