<?php
/**
 * Provides the HTML for the PinnerPress Pin It button.
 *
 * @link       https://pinnerpress.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */

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

/**
 * Darkens a hex color by a given factor
 *
 * @since 0.1.0
 * @param string $hex The hex color to darken (with or without #)
 * @param float $factor The factor to darken by (0-1, where 1 is no change and 0 is black)
 * @return string The darkened hex color with #
 */
function pinnerpress_darken_color($hex, $factor = 0.85) {
    // Remove # if present
    $hex = !empty($hex) ? str_replace('#', '', (string)$hex) : '';
    
    // Convert hex to RGB
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    
    // Darken each component
    $r = round($r * $factor);
    $g = round($g * $factor);
    $b = round($b * $factor);
    
    // Ensure values are within 0-255
    $r = max(0, min(255, $r));
    $g = max(0, min(255, $g));
    $b = max(0, min(255, $b));
    
    // Convert back to hex
    return '#' . str_pad(dechex($r), 2, '0', STR_PAD_LEFT) . 
                 str_pad(dechex($g), 2, '0', STR_PAD_LEFT) . 
                 str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
}

/**
 * Generates the HTML for the Pin It button.
 *
 * @since 0.1.0
 * @param array $options An array of button options.
 *      'position'          => (string) top-left, top-right, center, bottom-left, bottom-right.
 *      'shape'             => (string) round, rectangular.
 *      'size'              => (string) small, medium, large
 *      'color'             => (string) Hex color code for button background.
 *      'text_color'        => (string) Hex color code for button text.
 *      'image_shadow'      => (bool)   True to apply shadow, false otherwise.
 *      'custom_button_text'=> (string) The custom text for the button.
 *      'default_text'      => (string) Default text if not custom.
 *      'pinterest_title'   => (string) Custom Pinterest title specified in the block editor.
 *      'pinterest_text'    => (string) Custom Pinterest description specified in the block editor.
 *      'pinterest_repin_id'=> (string) Custom Pinterest repin ID specified in the block editor.
 *      'disable_pinning'   => (bool)   Whether pinning is disabled for this image.
 * @param bool $is_preview If true, renders a simplified version for admin preview.
 * @return string The HTML for the Pin It button or empty string if pinning is disabled.
 */
function pinnerpress_get_pin_button_html($options = [], $is_preview = false) {
    // Check if pinning is disabled for this specific image
    if (isset($options['disable_pinning']) && $options['disable_pinning']) {
        return '';
    }
    $defaults = [
        'position' => 'top-left',
        'shape' => 'rectangular',
        'size' => 'medium', // small, medium, large
        'color' => '#E60023', // Default Pinterest Red
        'text_color' => '#FFFFFF', // Default White text
        'image_shadow' => '0', // '0' or '1' from settings
        'custom_button_text' => '',
        'default_text' => 'Pin It',
        'image_url' => '', // Required for actual pinning
        'page_url' => '',  // Required for actual pinning
        'description' => '', // Required for actual pinning
        'button_style' => 'default', // Default or pinterest-logo (controls text visibility)
        'unique_id' => '' // Added for unique ID
    ];

    $settings = wp_parse_args($options, $defaults);

    $button_text = !empty($settings['custom_button_text']) ? $settings['custom_button_text'] : $settings['default_text'];
    $show_text = isset($settings['button_style']) ? $settings['button_style'] === 'default' : true;

    $style_attributes = [];
    $wrapper_style_attributes = ['position: absolute;', 'z-index: 10;']; // Wrapper is always absolute for positioning on image

    // Button Size
    $icon_size = '1em';
    $font_size = '14px';
    $padding = '8px 12px';
    $vertical_align = '-0.125em'; // Default vertical alignment
    
    switch ($settings['size']) {
        case 'small':
            $icon_size = '0.85em';
            $font_size = '12px';
            $padding = '6px 10px';
            $vertical_align = '-0.1em'; // Adjusted for small size
            break;
        case 'medium':
            $icon_size = '1em';
            $font_size = '14px';
            $padding = '8px 12px';
            $vertical_align = '-0.125em'; // Default alignment
            break;
        case 'large':
            $icon_size = '1.2em';
            $font_size = '16px';
            $padding = '10px 15px';
            $vertical_align = '-0.15em'; // Adjusted for large size
            break;
    }
    
    $style_attributes[] = 'display: inline-flex;';
    $style_attributes[] = 'align-items: center;';
    $style_attributes[] = 'font-size: ' . $font_size . ';';
    $style_attributes[] = 'font-weight: 500;';
    $style_attributes[] = 'padding: ' . $padding . ';';
    $style_attributes[] = 'text-decoration: none;';
    $style_attributes[] = 'cursor: pointer;';

    // Button Background and Text Color
    $style_attributes[] = 'background-color: ' . esc_attr($settings['color']) . ';';
    $style_attributes[] = 'color: ' . esc_attr($settings['text_color']) . ';';

    // Button Shape (via class, but border-radius can be inline too for simplicity here)
    if ($settings['shape'] === 'round') {
        $style_attributes[] = 'border-radius: 20px;'; // Adjust for desired roundness
    } else {
        $style_attributes[] = 'border-radius: 3px;'; // Slightly rounded rectangle
    }

    // Button Shadow
    if ($settings['image_shadow'] === '1') {
        $style_attributes[] = 'box-shadow: 0 2px 4px rgba(0,0,0,0.15);';
    }
    
    // Button Position
    $offset = '10px'; // Default offset from edges
    switch ($settings['position']) {
        case 'top-left':
            $wrapper_style_attributes[] = 'top: ' . $offset . ';';
            $wrapper_style_attributes[] = 'left: ' . $offset . ';';
            break;
        case 'top-right':
            $wrapper_style_attributes[] = 'top: ' . $offset . ';';
            $wrapper_style_attributes[] = 'right: ' . $offset . ';';
            break;
        case 'center':
            $wrapper_style_attributes[] = 'top: 50%;';
            $wrapper_style_attributes[] = 'left: 50%;';
            $wrapper_style_attributes[] = 'transform: translate(-50%, -50%);';
            break;
        case 'bottom-left':
            $wrapper_style_attributes[] = 'bottom: ' . $offset . ';';
            $wrapper_style_attributes[] = 'left: ' . $offset . ';';
            break;
        case 'bottom-right':
            $wrapper_style_attributes[] = 'bottom: ' . $offset . ';';
            $wrapper_style_attributes[] = 'right: ' . $offset . ';';
            break;
    }

    // Button classes
    $button_classes = ['pinnerpress-pin-it-button'];
    
    // Add unique ID class if provided to help prevent duplication issues
    if (isset($settings['unique_id'])) {
        $button_classes[] = 'pinnerpress-pin-instance-' . esc_attr($settings['unique_id']);
    }

    $button_html_tag = $is_preview ? 'span' : 'a';
    $href_attribute = '';

    if (!$is_preview) {
        $pinterest_pin_url = 'https://www.pinterest.com/pin/create/button/';
        
        // Use custom Pinterest description if available, fallback to regular description
        // This ensures block-level attributes have priority
        $description = '';
        
        // 1. First priority: Block-level custom description
        if (isset($settings['pinterest_text']) && !empty($settings['pinterest_text'])) {
            $description = $settings['pinterest_text'];
        }
        // 2. Second priority: Default description
        else if (!empty($settings['description'])) {
            $description = $settings['description'];
        }
        // 3. Fallback: Page title
        else {
            $description = get_the_title();
        }
            
        // Prepare the query arguments
        $query_args = [
            'url' => rawurlencode($settings['page_url']),
            'media' => rawurlencode($settings['image_url']),
            'description' => rawurlencode($description),
            'method' => 'button'
        ];
        
        // Add title if available (block-level attribute has priority)
        if (isset($settings['pinterest_title']) && !empty($settings['pinterest_title'])) {
            $query_args['title'] = rawurlencode($settings['pinterest_title']);
        } 
        // Otherwise use default page title
        else {
            $query_args['title'] = rawurlencode(get_the_title());
        }
        
        // Add repin ID if available
        if (isset($settings['pinterest_repin_id']) && !empty($settings['pinterest_repin_id'])) {
            $query_args['id'] = rawurlencode($settings['pinterest_repin_id']);
        }
        
        $href_attribute = 'href="' . esc_url(add_query_arg($query_args, $pinterest_pin_url)) . '" target="_blank" rel="noopener noreferrer" data-pin-do="buttonBookmark" data-pin-custom="true"';
    }


    $html = sprintf(
        '<div class="pinnerpress-pin-it-button-wrapper" style="%s">',
        implode(' ', $wrapper_style_attributes)
    );
    $html .= sprintf(
        '<%s class="%s" style="%s" %s data-pinnerpress-button="true">',
        $button_html_tag,
        implode(' ', $button_classes),
        implode(' ', $style_attributes),
        $href_attribute
    );
    // Add Pinterest Icon (SVG)
    $html .= '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="pinnerpress-pin-icon" style="width: ' . $icon_size . '; height: ' . $icon_size . '; vertical-align: ' . $vertical_align . '; margin-right: ' . ($show_text ? '0.3em' : '0') . '; fill: currentColor; shape-rendering: geometricPrecision; text-rendering: optimizeLegibility; image-rendering: optimizeQuality;"><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></svg>';
    
    // Only add text if show_text is true
    if ($show_text) {
        $html .= esc_html($button_text);
    }
    
    $html .= sprintf('</%s></div>', $button_html_tag);

    return $html;
} 