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

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

/**
 * Register the Pinterest Callout Banner block
 */
function pinnerpress_register_callout_banner_block() {
    // This is a premium feature
    if (!pinnerpress_is_premium()) {
        return;
    }
    
    // Check if the feature is enabled
    if (!pinnerpress_is_feature_enabled('call_out_banners')) {
        return;
    }
    
    // Check if call out banner is enabled in settings
    if (get_option('pinnerpress_call_out_status', 'off') !== 'on') {
        return;
    }

    // Check if Gutenberg is available
    if (!function_exists('register_block_type')) {
        return;
    }

    // Register the block script
    wp_register_script(
        'pinnerpress-callout-block',
        plugin_dir_url(dirname(__FILE__)) . 'admin/js/pinnerpress-callout-block.js',
        array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n'),
        PINNERPRESS_VERSION,
        true
    );
    
    // Localize script with default settings
    wp_localize_script('pinnerpress-callout-block', 'pinnerpressCalloutDefaults', array(
        'pinterestUrl' => get_option('pinnerpress_pinterest_url', ''),
        'bgColor' => get_option('pinnerpress_call_out_bg_color', '#E60023'),
        'borderColor' => get_option('pinnerpress_call_out_border_color', '#E60023'),
        'textColor' => get_option('pinnerpress_call_out_text_color', '#FFFFFF'),
        'title' => get_option('pinnerpress_call_out_title', __('Follow us on Pinterest', 'pinnerpress')),
        'buttonText' => get_option('pinnerpress_call_out_button_text', __('Follow', 'pinnerpress')),
        'buttonBgColor' => get_option('pinnerpress_call_out_button_bg_color', '#FFFFFF'),
        'buttonTextColor' => get_option('pinnerpress_call_out_button_text_color', '#E60023'),
        'logo' => get_option('pinnerpress_call_out_logo', 'pinterest'),
        'profileImage' => get_option('pinnerpress_profile_image', '')
    ));

    // Register the block editor style
    wp_register_style(
        'pinnerpress-callout-block-editor',
        plugin_dir_url(dirname(__FILE__)) . 'admin/css/pinnerpress-callout-block-editor.css',
        array('wp-edit-blocks'),
        PINNERPRESS_VERSION
    );

    // Register the block frontend style (moved to public/css)
    wp_register_style(
        'pinnerpress-callout-block',
        plugin_dir_url(dirname(__FILE__)) . 'public/css/pinnerpress-callout-block.css',
        array(),
        PINNERPRESS_VERSION
    );

    // Register the block
    register_block_type('pinnerpress/callout-banner', array(
        'editor_script' => 'pinnerpress-callout-block',
        'editor_style' => 'pinnerpress-callout-block-editor',
        'style' => 'pinnerpress-callout-block',
        'render_callback' => 'pinnerpress_render_callout_block',
        'attributes' => array(
            'pinterestUrl' => array(
                'type' => 'string',
                'default' => ''
            ),
            'bgColor' => array(
                'type' => 'string',
                'default' => ''
            ),
            'borderColor' => array(
                'type' => 'string',
                'default' => ''
            ),
            'textColor' => array(
                'type' => 'string',
                'default' => ''
            ),
            'title' => array(
                'type' => 'string',
                'default' => ''
            ),
            'buttonText' => array(
                'type' => 'string',
                'default' => ''
            ),
            'buttonBgColor' => array(
                'type' => 'string',
                'default' => ''
            ),
            'buttonTextColor' => array(
                'type' => 'string',
                'default' => ''
            ),
            'logo' => array(
                'type' => 'string',
                'default' => 'pinterest'
            ),
            'openInNewTab' => array(
                'type' => 'boolean',
                'default' => true
            )
        )
    ));
}

/**
 * Render the Pinterest Callout Banner block on the frontend
 */
function pinnerpress_render_callout_block($attributes) {
    // Get defaults from settings
    $default_pinterest_url = get_option('pinnerpress_pinterest_url', '');
    $default_bg_color = get_option('pinnerpress_call_out_bg_color', '#E60023');
    $default_border_color = get_option('pinnerpress_call_out_border_color', '#E60023');
    $default_text_color = get_option('pinnerpress_call_out_text_color', '#FFFFFF');
    $default_title = get_option('pinnerpress_call_out_title', __('Follow us on Pinterest', 'pinnerpress'));
    $default_button_text = get_option('pinnerpress_call_out_button_text', __('Follow', 'pinnerpress'));
    $default_button_bg_color = get_option('pinnerpress_call_out_button_bg_color', '#FFFFFF');
    $default_button_text_color = get_option('pinnerpress_call_out_button_text_color', '#E60023');
    $default_logo = get_option('pinnerpress_call_out_logo', 'pinterest');
    
    // Use block attributes or fall back to defaults
    $pinterest_url = !empty($attributes['pinterestUrl']) ? esc_url($attributes['pinterestUrl']) : $default_pinterest_url;
    $bg_color = !empty($attributes['bgColor']) ? esc_attr($attributes['bgColor']) : $default_bg_color;
    $border_color = !empty($attributes['borderColor']) ? esc_attr($attributes['borderColor']) : $default_border_color;
    $text_color = !empty($attributes['textColor']) ? esc_attr($attributes['textColor']) : $default_text_color;
    $title = !empty($attributes['title']) ? esc_html($attributes['title']) : $default_title;
    $button_text = !empty($attributes['buttonText']) ? esc_html($attributes['buttonText']) : $default_button_text;
    $button_bg_color = !empty($attributes['buttonBgColor']) ? esc_attr($attributes['buttonBgColor']) : $default_button_bg_color;
    $button_text_color = !empty($attributes['buttonTextColor']) ? esc_attr($attributes['buttonTextColor']) : $default_button_text_color;
    $logo = !empty($attributes['logo']) ? esc_attr($attributes['logo']) : $default_logo;
    $open_in_new_tab = isset($attributes['openInNewTab']) ? $attributes['openInNewTab'] : true;

    // If no Pinterest URL is provided, don't render anything
    if (empty($pinterest_url)) {
        return '';
    }

    // Ensure the URL is properly formatted
    if (!preg_match('~^https?://~i', $pinterest_url)) {
        $pinterest_url = 'https://' . $pinterest_url;
    }
    
    // Target attribute
    $target = $open_in_new_tab ? ' target="_blank" rel="noopener noreferrer"' : '';

    // Build logo HTML (exact same as existing implementation)
    $logo_html = '';
    if ($logo === 'pinterest') {
        $logo_html = '<div class="pinnerpress-logo" style="display: flex; align-items: center; justify-content: flex-start; margin-right: 15px; width: auto; min-width: 38px; flex-shrink: 0;">';
        $logo_html .= '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width: 38px; height: 38px; fill: ' . esc_attr($text_color) . ';">';
        $logo_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>';
        $logo_html .= '</svg>';
        $logo_html .= '</div>';
    } elseif ($logo === 'profile') {
        // Get profile image URL
        $profile_image = get_option('pinnerpress_profile_image', '');
        
        // If no custom profile image is set, use the default one
        if (empty($profile_image)) {
            $profile_image = esc_url(plugin_dir_url(dirname(__FILE__)) . 'public/images/follow-box/default-pinterest-profile-images.png');
        }
        
        $logo_html = '<div class="pinnerpress-logo" style="display: flex; align-items: center; justify-content: flex-start; margin-right: 15px; width: auto; min-width: 38px; flex-shrink: 0;">';
        $logo_html .= '<img src="' . esc_url($profile_image) . '" alt="Profile" style="width: 38px; height: 38px; border-radius: 50%;" />';
        $logo_html .= '</div>';
    }

    // Wrap in a container div for block context
    $banner_html = '<div class="wp-block-pinnerpress-callout-banner">';
    
    // Generate the banner HTML (exact same as the existing implementation)
    $banner_html .= '<div class="pinnerpress-call-out-banner" style="background-color: ' . esc_attr($bg_color) . '; color: ' . esc_attr($text_color) . '; padding: 15px 25px; border-radius: 6px; display: flex; align-items: center; justify-content: space-between; text-align: center; flex-wrap: nowrap; margin: 30px 0;">';
    
    // Add logo HTML if available
    if (!empty($logo_html)) {
        $banner_html .= $logo_html;
    }
    
    // Replace h3 with span for the title (exact same as existing)
    $banner_html .= '<span style="color: ' . esc_attr($text_color) . ' !important; font-weight: 600; margin: 0; font-size: 24px !important; text-align: center; flex: 1; display: flex; justify-content: center; align-items: center;">' . esc_html($title) . '</span>';
    
    // Add button on right (pill shaped) with tracking attribute
    $banner_html .= '<a href="' . esc_url($pinterest_url) . '"' . $target . ' class="pinnerpress-call-out-button" data-pinnerpress-track="call_out_banner_click" style="display: inline-block; background-color: ' . esc_attr($button_bg_color) . ' !important; padding: 8px 15px; text-decoration: none !important; border-radius: 50px; font-weight: 700; white-space: nowrap; margin-left: 15px; min-width: 90px; text-align: center; flex-shrink: 0; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); font-size: 16px; line-height: 1.4;">';
    $banner_html .= '<span style="color: ' . esc_attr($button_text_color) . ' !important;">' . esc_html($button_text) . '</span>';
    $banner_html .= '</a>';
    
    $banner_html .= '</div>';
    
    // Add responsive styles for mobile (exact same as existing)
    $banner_html .= '<style>
        @media (max-width: 768px) {
            .pinnerpress-call-out-banner {
                flex-direction: column;
                padding: 20px;
                align-items: center;
            }
            /* Target the title span specifically for its mobile margin */
            .pinnerpress-call-out-banner > span:not(.pinnerpress-button-text-span) { 
                margin: 10px 0 10px 0 !important; /* Reduced bottom margin, or set to 0 if no extra margin needed */
                text-align: center;
                display: block;
                width: 100%;
            }
            .pinnerpress-call-out-button {
                width: 100%;
                max-width: 200px;
                margin: 0 auto 5px !important; /* Adjusted button margin */
                padding: 6px 12px !important; /* Reduced padding for mobile */
            }
            .pinnerpress-call-out-button span.pinnerpress-button-text-span {
                margin: 0 !important; /* Ensure no extra margin on button text */
                padding: 0 !important; /* Ensure no extra padding on button text */
            }
            .pinnerpress-logo {
                margin: 0 auto 10px !important;
            }
        }
    </style>';
    
    // Close the wrapper div
    $banner_html .= '</div>';

    return $banner_html;
}

/**
 * Hook to register the block
 */
add_action('init', 'pinnerpress_register_callout_banner_block');