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

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

/**
 * Insert hidden pins button after post title
 *
 * @since    0.1.0
 * @param    string    $content    The post content
 * @return   string                The modified content with button
 */
function pinnerpress_insert_hidden_pins_button($content) {
    // Check if hidden pins feature is available
    if (!function_exists('pinnerpress_is_feature_enabled') || !pinnerpress_is_feature_enabled('enable_hidden_pins')) {
        return $content;
    }
    
    // Check if hidden pins button is enabled
    if (get_option('pinnerpress_enable_hidden_pins', '0') !== '1') {
        return $content;
    }
    
    // Only show on single posts, not on homepage or archive pages
    if (!is_single() || is_home() || is_front_page()) {
        return $content;
    }
    
    // Get the current post ID
    $post_id = get_the_ID();
    if (!$post_id) {
        return $content;
    }
    
    // Get pin button colors from settings
    $button_bg_color = get_option('pinnerpress_hover_button_color', '#E60023');
    $button_text_color = get_option('pinnerpress_hover_button_text_color', '#FFFFFF');
    
    // Create the button HTML
    $button_html = '<div class="pinnerpress-hidden-pins-button-wrapper" style="margin: 20px 0;">';
    $button_html .= '<button type="button" class="pinnerpress-hidden-pins-button" data-post-id="' . esc_attr($post_id) . '" style="';
    $button_html .= 'background-color: ' . esc_attr($button_bg_color) . ';';
    $button_html .= 'color: ' . esc_attr($button_text_color) . ';';
    $button_html .= 'border: none;';
    $button_html .= 'padding: 10px 20px;';
    $button_html .= 'font-size: 16px;';
    $button_html .= 'font-weight: 600;';
    $button_html .= 'border-radius: 4px;';
    $button_html .= 'cursor: pointer;';
    $button_html .= 'display: inline-flex;';
    $button_html .= 'align-items: center;';
    $button_html .= 'gap: 8px;';
    $button_html .= 'transition: background-color 0.3s ease;';
    $button_html .= '">';
    
    // Add Pinterest icon
    $button_html .= '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: currentColor;">';
    $button_html .= '<path d="M12 0C5.373 0 0 5.373 0 12c0 4.99 3.657 9.132 8.48 10.099-.118-.859-.224-2.178.045-3.116.244-.834 1.577-5.313 1.577-5.313s-.402-.803-.402-1.986c0-1.863 1.08-3.254 2.42-3.254 1.142 0 1.693.859 1.693 1.89 0 1.151-.733 2.87-1.11 4.467-.318 1.322.672 2.401 1.99 2.401 2.388 0 4.224-2.516 4.224-6.14 0-3.204-2.303-5.442-5.581-5.442-3.803 0-6.037 2.849-6.037 5.794 0 1.148.438 2.382 1.054 3.049.117.13.134.244.099.377-.109.427-.354 1.35-.398 1.539-.062.248-.2.302-.461.182-1.723-.796-2.797-3.294-2.797-5.301 0-4.33 3.141-8.306 9.067-8.306 4.754 0 8.442 3.384 8.442 7.917 0 4.715-2.969 8.502-7.085 8.502-1.381 0-2.681-.712-3.123-1.557l-.847 3.216c-.306 1.156-1.14 2.6-1.699 3.487C9.19 23.414 10.573 24 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0z"></path>';
    $button_html .= '</svg>';
    
    $button_html .= '<span>' . esc_html__('Save This On Pinterest!', 'pinnerpress') . '</span>';
    $button_html .= '</button>';
    $button_html .= '</div>';
    
    // Calculate darker hover color
    $hover_color = pinnerpress_darken_color($button_bg_color, 0.85);
    
    // Add button hover style
    $button_html .= '<style>';
    $button_html .= '.pinnerpress-hidden-pins-button:hover { background-color: ' . esc_attr($hover_color) . ' !important; }';
    $button_html .= '</style>';
    
    // Hook the modal printing function to the footer
    add_action('wp_footer', 'pinnerpress_print_hidden_pins_modal_action');
    
    // Return button followed by content
    return $button_html . $content;
}

/**
 * Print the hidden pins modal HTML in the footer
 *
 * @since 0.1.0
 */
function pinnerpress_print_hidden_pins_modal_action() {
    // Ensure it's only added once
    static $modal_printed = false;
    if ($modal_printed) {
        return;
    }
    
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Modal HTML is properly escaped internally
    echo pinnerpress_get_hidden_pins_modal_html();
    $modal_printed = true;
}

/**
 * Get the HTML for the hidden pins modal
 *
 * @since    0.1.0
 * @return   string    Modal HTML
 */
function pinnerpress_get_hidden_pins_modal_html() {
    $modal_html = '<div id="pinnerpress-hidden-pins-modal" class="pinnerpress-modal" style="display: none;">';
    $modal_html .= '<div class="pinnerpress-modal-overlay"></div>';
    $modal_html .= '<div class="pinnerpress-modal-content">';
    $modal_html .= '<div class="pinnerpress-modal-header">';
    $modal_html .= '<h2>' . esc_html__('Choose a Pin to save', 'pinnerpress') . '</h2>';
    $modal_html .= '<button type="button" class="pinnerpress-modal-close" aria-label="' . esc_attr__('Close', 'pinnerpress') . '">&times;</button>';
    $modal_html .= '</div>';
    $modal_html .= '<div class="pinnerpress-modal-body">';
    $modal_html .= '<div class="pinnerpress-modal-loading">';
    $modal_html .= '<div class="pinnerpress-spinner"></div>';
    $modal_html .= '<p>' . esc_html__('Loading images...', 'pinnerpress') . '</p>';
    $modal_html .= '</div>';
    $modal_html .= '<div class="pinnerpress-modal-images-grid" style="display: none;"></div>';
    $modal_html .= '</div>';
    $modal_html .= '</div>';
    $modal_html .= '</div>';
    
    // Add modal styles
    $modal_html .= '<style>';
    $modal_html .= '#pinnerpress-hidden-pins-modal {
        position: fixed !important;
        top: 0 !important;
        left: 0 !important;
        width: 100% !important;
        height: 100% !important;
        z-index: 999999 !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
    }
    #pinnerpress-hidden-pins-modal[style*="display: none"] {
        display: none !important;
    }
    .pinnerpress-modal-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
    }
    .pinnerpress-modal-content {
        position: relative;
        width: 80%;
        height: 80%;
        max-width: 1400px;
        background: white;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
    .pinnerpress-modal-header {
        padding: 20px 30px;
        background: white;
        border-bottom: 1px solid #e7e7e7;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-shrink: 0;
    }
    .pinnerpress-modal-header h2 {
        margin: 0;
        font-size: 24px;
        color: #333;
    }
    .pinnerpress-modal-close {
        background: transparent;
        border: none;
        font-size: 32px;
        color: #666;
        cursor: pointer;
        padding: 0;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s ease;
    }
    .pinnerpress-modal-close:hover {
        color: #E60023;
        transform: scale(1.1);
    }
    .pinnerpress-modal-body {
        padding: 30px;
        overflow-y: auto;
        flex: 1;
    }
    .pinnerpress-modal-loading {
        text-align: center;
        padding: 40px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .pinnerpress-spinner {
        border: 3px solid #f3f3f3;
        border-top: 3px solid #E60023;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        animation: spin 1s linear infinite;
        margin: 0 auto 20px;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    .pinnerpress-modal-images-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 20px;
    }
    .pinnerpress-modal-image-item {
        position: relative;
        border-radius: 8px;
        overflow: hidden;
        background: #f5f5f5;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s ease, box-shadow 0.2s ease;
        aspect-ratio: 3/4;
    }
    .pinnerpress-modal-image-item:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    }
    .pinnerpress-modal-image-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
    }
    .pinnerpress-modal-image-item .pinnerpress-pin-it-button-wrapper {
        opacity: 1 !important;
        visibility: visible !important;
        display: block !important;
        z-index: 100 !important;
    }
    .pinnerpress-modal-image-item .pinnerpress-pin-it-container {
        width: 100% !important;
        height: 100% !important;
    }
    @media (max-width: 1200px) {
        .pinnerpress-modal-content {
            width: 90%;
            height: 85%;
        }
        .pinnerpress-modal-images-grid {
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 15px;
        }
    }
    @media (max-width: 768px) {
        .pinnerpress-modal-content {
            width: 95%;
            height: 90%;
        }
        .pinnerpress-modal-header {
            padding: 15px 20px;
        }
        .pinnerpress-modal-header h2 {
            font-size: 20px;
        }
        .pinnerpress-modal-close {
            width: 35px;
            height: 35px;
            font-size: 28px;
        }
        .pinnerpress-modal-body {
            padding: 20px;
        }
        .pinnerpress-modal-images-grid {
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
        }
    }
    </style>';
    
    return $modal_html;
}

/**
 * Handle AJAX request to get images for the modal
 *
 * @since    0.1.0
 */
function pinnerpress_ajax_get_modal_images() {
    // Check nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'pinnerpress_analytics_nonce')) {
        wp_send_json_error('Invalid nonce');
        return;
    }
    
    // Get post ID
    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    if (!$post_id) {
        wp_send_json_error('Invalid post ID');
        return;
    }
    
    // Get hidden images for this post
    $hidden_images = get_post_meta($post_id, '_pinnerpress_hidden_images', true);
    $images = array();
    
    // First, add hidden images if they exist
    if (!empty($hidden_images) && is_array($hidden_images)) {
        foreach ($hidden_images as $image) {
            if (!empty($image['url'])) {
                $images[] = array(
                    'url' => $image['url'],
                    'id' => 'hidden-' . md5($image['url']),
                    'is_hidden' => true
                );
            }
        }
    }
    
    // Then, always add all images from the post content
    $post = get_post($post_id);
    if (!$post) {
        wp_send_json_error('Post not found');
        return;
    }

    // Check if custom selectors are enabled
    $custom_selectors_enabled = get_option('pinnerpress_custom_selectors_enabled', '0') === '1';
    $custom_selectors = get_option('pinnerpress_custom_selectors', '');
    $find_images_in_selectors = get_option('pinnerpress_find_images_in_selectors', '0') === '1';

    $content_images = array();

    // Get the rendered content (this applies filters like shortcodes, blocks, etc.)
    $content = apply_filters('the_content', $post->post_content);

    // Also try the raw content as fallback
    $raw_content = $post->post_content;

    if ($custom_selectors_enabled && !empty($custom_selectors)) {
        // Use custom selectors to find images
        // Try with rendered content first
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML('<?xml encoding="UTF-8">' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
        libxml_clear_errors();

        $xpath = new DOMXPath($dom);

        // Split selectors by newline and clean them
        $selectors = array_filter(array_map('trim', explode("\n", $custom_selectors)));

        if (!empty($selectors)) {
            foreach ($selectors as $selector) {
                // Convert CSS selector to XPath
                $xpath_query = pinnerpress_css_to_xpath($selector, $find_images_in_selectors);

                if ($xpath_query) {
                    $nodes = $xpath->query($xpath_query);
                    if ($nodes && $nodes->length > 0) {
                        foreach ($nodes as $node) {
                            if ($node instanceof DOMElement) {
                                $img_url = $node->getAttribute('src');
                                // Skip SVG placeholders and data URLs
                                if (!empty($img_url) &&
                                    strpos($img_url, 'data:image/svg') === false &&
                                    strpos($img_url, 'data:image/gif') === false) {
                                    $content_images[] = $img_url;
                                }
                            }
                        }
                    }
                }
            }
        }

        // Remove duplicates
        $content_images = array_unique($content_images);
    } else {
        // Use default regex approach to find all images
        // Try rendered content first
        preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches);

        if (!empty($matches[1])) {
            foreach ($matches[1] as $img_url) {
                // Skip SVG placeholders and data URLs
                if (strpos($img_url, 'data:image/svg') === false &&
                    strpos($img_url, 'data:image/gif') === false) {
                    $content_images[] = $img_url;
                }
            }
        }

        // If no images found in rendered content, try raw content
        if (empty($content_images)) {
            preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $raw_content, $raw_matches);
            if (!empty($raw_matches[1])) {
                foreach ($raw_matches[1] as $img_url) {
                    // Skip SVG placeholders and data URLs
                    if (strpos($img_url, 'data:image/svg') === false &&
                        strpos($img_url, 'data:image/gif') === false) {
                        $content_images[] = $img_url;
                    }
                }
            }
        }

        // Remove duplicates
        $content_images = array_unique($content_images);
    }

    // Add content images to the main images array
    foreach ($content_images as $img_url) {
        $images[] = array(
            'url' => $img_url,
            'id' => 'content-' . md5($img_url),
            'is_hidden' => false
        );
    }

    // Also check for featured image and add it at the beginning of content images
    if (has_post_thumbnail($post_id)) {
        $featured_img_url = get_the_post_thumbnail_url($post_id, 'full');
        if ($featured_img_url) {
            // Find the position where content images start (after hidden images)
            $content_start_index = 0;
            foreach ($images as $index => $image) {
                if (!$image['is_hidden']) {
                    $content_start_index = $index;
                    break;
                }
            }

            // Insert featured image at the beginning of content images
            array_splice($images, $content_start_index, 0, array(array(
                'url' => $featured_img_url,
                'id' => 'featured-' . $post_id,
                'is_hidden' => false
            )));
        }
    }
    
    // Get post data for Pinterest
    $post_url = get_permalink($post_id);
    $post_title = get_the_title($post_id);
    
    wp_send_json_success(array(
        'images' => $images,
        'post_url' => $post_url,
        'post_title' => $post_title,
        'has_hidden_images' => !empty($hidden_images)
    ));
}

/**
 * Convert CSS selector to XPath query
 *
 * @since    0.1.0
 * @param    string     $selector                   CSS selector
 * @param    bool       $find_images_in_selector    Whether to find images within the selector
 * @return   string                                 XPath query
 */
function pinnerpress_css_to_xpath($selector, $find_images_in_selector = false) {
    // Trim the selector
    $selector = trim($selector);

    if (empty($selector)) {
        return '';
    }

    $xpath = '';

    // Handle class selectors (.classname)
    if (preg_match('/^\.([a-zA-Z0-9_-]+)$/', $selector, $matches)) {
        $class = $matches[1];
        $xpath = "//*[contains(concat(' ', normalize-space(@class), ' '), ' {$class} ')]";
    }
    // Handle ID selectors (#id)
    elseif (preg_match('/^#([a-zA-Z0-9_-]+)$/', $selector, $matches)) {
        $id = $matches[1];
        $xpath = "//*[@id='{$id}']";
    }
    // Handle element selectors (div, img, etc.)
    elseif (preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/', $selector)) {
        $xpath = "//{$selector}";
    }
    // Handle element.class selectors (div.classname)
    elseif (preg_match('/^([a-zA-Z][a-zA-Z0-9]*)\.([a-zA-Z0-9_-]+)$/', $selector, $matches)) {
        $element = $matches[1];
        $class = $matches[2];
        $xpath = "//{$element}[contains(concat(' ', normalize-space(@class), ' '), ' {$class} ')]";
    }
    // Handle descendant selectors (.class img or div img)
    elseif (preg_match('/^(.+)\s+([a-zA-Z][a-zA-Z0-9]*)$/', $selector, $matches)) {
        $parent = trim($matches[1]);
        $child = $matches[2];
        $parent_xpath = pinnerpress_css_to_xpath($parent, false);
        if ($parent_xpath) {
            $xpath = "{$parent_xpath}//{$child}";
        }
    }
    // Fallback: try to handle as element name
    else {
        // For complex selectors we can't parse, just look for img tags
        $xpath = '//img';
    }

    // If we should find images within this selector and it's not already selecting img tags
    if ($find_images_in_selector && !empty($xpath) && strpos($xpath, '//img') === false) {
        $xpath .= '//img';
    }

    // If not finding images in selector and the selector doesn't specify img, default to img
    if (!$find_images_in_selector && !empty($xpath) && strpos($selector, 'img') === false) {
        // The selector should point to img elements directly
        // If it doesn't contain 'img', we assume it's a container and look for img inside
        $xpath .= '//img';
    }

    return $xpath;
}

/**
 * Initialize hidden pins button functionality
 *
 * @since    0.1.0
 */
function pinnerpress_init_hidden_pins_button() {
    // Add filter to insert button after title
    add_filter('the_content', 'pinnerpress_insert_hidden_pins_button', 5);

    // Add AJAX handler
    add_action('wp_ajax_pinnerpress_get_modal_images', 'pinnerpress_ajax_get_modal_images');
    add_action('wp_ajax_nopriv_pinnerpress_get_modal_images', 'pinnerpress_ajax_get_modal_images');
}

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