<?php
/**
 * Reusable Cover Photo Component
 *
 * Provides a consistent cover photo display across all block templates.
 *
 * @since 4.2.0
 */

// Ensure we have the required data
if (!isset($user) || !is_object($user) || !isset($user->ID)) {
    return;
}

// Check if current user can edit this profile
$can_edit = false;
if ( class_exists( 'WPUF\UserDirectory\Blocks' ) ) {
    $blocks_instance = new WPUF\UserDirectory\Blocks();
    $can_edit = $blocks_instance->can_user_edit_profile( $user );
}

// Get component options
$options = $options ?? [];
$defaults = [
    'cover_height' => 300,
    'cover_width' => 'full-width',
    'custom_width_value' => 800,
    'custom_width_unit' => 'px',
    'fit_type' => 'cover',
    'fallback_type' => 'placeholder',
    'link_to_profile' => false,
    'link_target' => '_self',
    'placeholder_color' => '#f3f4f6',
    'class' => '',
];

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

// Get cover photo URL using the proper function that handles attachment ID to URL conversion
// Calculate width based on cover_width setting
if ($options['cover_width'] === 'custom') {
    $cover_width_value = $options['custom_width_unit'] === 'px'
        ? intval($options['custom_width_value'] ?? 800)
        : 1200; // For %, use a reasonable default for image fetching
} else {
    $cover_width_value = 1200; // Full width uses 1200px
}
$cover_photo_data = wpuf_ud_get_block_cover_photo_data($user, $cover_width_value);
$cover_photo_url = $cover_photo_data['url'];

// Get author URL for linking
$author_url = get_author_posts_url($user->ID);
$target_attr = $options['link_target'] === '_blank' ? ' target="_blank" rel="noopener"' : '';

// Build CSS classes
$css_classes = ['wpuf-cover-photo'];
$css_classes[] = 'wpuf-cover-photo--' . $options['cover_width'];
$css_classes[] = 'wpuf-cover-photo--' . $options['fit_type'];

if (!empty($options['class'])) {
    $css_classes[] = esc_attr($options['class']);
}

// Build inline styles for height (set directly, not via CSS variable)
$cover_height = intval($options['cover_height'] ?? 300);

$inline_styles = sprintf(
    'height: %dpx;',
    $cover_height
);

// Add custom width styles if custom width is selected
if ($options['cover_width'] === 'custom') {
    $custom_width_value = intval($options['custom_width_value'] ?? 800);
    $custom_width_unit = $options['custom_width_unit'] ?? 'px';

    if ($custom_width_unit === 'px') {
        $inline_styles .= sprintf(' width: %dpx; max-width: %dpx;', $custom_width_value, $custom_width_value);
    } else {
        $inline_styles .= sprintf(' width: %d%%; max-width: %d%%;', $custom_width_value, $custom_width_value);
    }
    $inline_styles .= ' margin: 0 auto;';
}

// Render cover photo or fallback
$cover_photo_content = '';

if (!empty($cover_photo_url)) {
    // User has a cover photo
    $cover_photo_content = sprintf(
        '<img src="%s" alt="%s" class="wpuf-cover-photo__image" style="%s" />',
        esc_url($cover_photo_url),
        esc_attr(sprintf('%s %s', $user->display_name, __('Cover Photo', 'wpuf-pro'))),
        esc_attr($inline_styles)
    );
} else {
    // No cover photo - show fallback
    if ($options['fallback_type'] === 'placeholder') {
        $cover_photo_content = sprintf(
            '<div class="wpuf-cover-photo__placeholder" style="background-color: %s; %s">
                <span class="wpuf-cover-photo__placeholder-text">%s</span>
            </div>',
            esc_attr($options['placeholder_color']),
            esc_attr($inline_styles),
            esc_html__('', 'wpuf-pro')
        );
    } else if ($options['fallback_type'] === 'solid') {
        $cover_photo_content = sprintf(
            '<div class="wpuf-cover-photo__solid" style="background-color: %s; %s"></div>',
            esc_attr($options['placeholder_color']),
            esc_attr($inline_styles)
        );
    }
}

// Build the final HTML
$container_class = 'wpuf-cover-photo__container';
if ($can_edit) {
    $container_class .= ' wpuf-cover-photo__container--editable';
}

$container_styles = '';
if ($can_edit) {
    $container_styles = 'position: relative;';
}

// Only show upload button in User Profile block, not in User Directory block
$is_profile_mode = isset( $is_profile_mode ) ? $is_profile_mode : false;
$show_upload_button = $can_edit && $is_profile_mode;

$final_html = sprintf(
    '<div class="%s" style="%s">
        <div class="%s" style="%s">
            %s
            %s
        </div>
    </div>',
    esc_attr(implode(' ', $css_classes)),
    esc_attr($inline_styles),
    esc_attr($container_class),
    esc_attr($container_styles),
    $cover_photo_content,
    $show_upload_button ? sprintf(
        '<button type="button"
                class="wpuf-cover-photo-upload-btn wpuf-absolute wpuf-inset-0 wpuf-flex wpuf-items-center wpuf-justify-center wpuf-bg-black wpuf-bg-opacity-50 wpuf-text-white wpuf-text-sm wpuf-font-medium wpuf-opacity-0 wpuf-transition-opacity wpuf-duration-200 wpuf-cursor-pointer hover:wpuf-bg-opacity-70 focus:wpuf-outline-none focus:wpuf-ring-2 focus:wpuf-ring-green-500 focus:wpuf-ring-opacity-50"
                onclick="wpufOpenCoverPhotoUpload(%d)"
                title="%s"
                aria-label="%s">
            <span class="wpuf-cover-photo-upload-text">%s</span>
        </button>',
        esc_attr($user->ID),
        esc_attr__('Upload Cover Photo', 'wpuf-pro'),
        esc_attr__('Upload Cover Photo', 'wpuf-pro'),
        esc_html__('Upload', 'wpuf-pro')
    ) : ''
);

// Wrap in link if needed
if ($options['link_to_profile'] && !empty($author_url)) {
    $final_html = sprintf(
        '<a href="%s"%s class="wpuf-cover-photo__link">%s</a>',
        esc_url($author_url),
        $target_attr,
        $final_html
    );
}

// Output the component
echo $final_html;
