<?php
// If this file is called directly, abort.
if (! defined('ABSPATH')) {
    exit;
}

/**
 * Main render entry point for the Product Attributes widget.
 *
 * @param \GGM_Commerce_Base_Widget $widget The widget instance.
 */
function ggmc_product_attributes_render( $widget ) {
    $settings = $widget->get_settings_for_display();

    // Get product data (includes preview product support)
    $product_data = $widget->get_product_data();

    // Get units from settings
    $units_options = get_option('ggm_commerce_units_options', []);
    $weight_unit = isset($units_options['weight_unit']) ? $units_options['weight_unit'] : 'kg';
    $dimension_unit = isset($units_options['dimension_unit']) ? $units_options['dimension_unit'] : 'cm';

    // Get values
    $weight = null;
    $length = null;
    $width  = null;
    $height = null;

    if ($product_data) {
        $weight = isset($product_data->weight) ? $product_data->weight : null;
        $length = isset($product_data->length) ? $product_data->length : null;
        $width  = isset($product_data->width)  ? $product_data->width  : null;
        $height = isset($product_data->height) ? $product_data->height : null;
    }

    // Check if we should show in editor mode with placeholder values
    $is_editor = ggmc_is_editor_mode();
    if ($is_editor && ! $product_data) {
        $weight = 1.5;
        $length = 30;
        $width  = 20;
        $height = 10;
    }

    // Check if widget should be hidden when empty
    $has_weight     = ! empty($weight) && $settings['show_weight'] === 'yes';
    $has_dimensions = (! empty($length) || ! empty($width) || ! empty($height)) && $settings['show_dimensions'] === 'yes';

    if ($settings['hide_empty'] === 'yes' && ! $has_weight && ! $has_dimensions && ! $is_editor) {
        return; // Don't output anything
    }

    // Build attributes data
    $attributes = [];

    if ($settings['show_weight'] === 'yes' && ($has_weight || $is_editor)) {
        $weight_value = $weight ? number_format((float) $weight, 2) : '—';
        if ($settings['show_units'] === 'yes' && $weight) {
            $weight_value .= ' ' . $weight_unit;
        }
        $attributes[] = [
            'label' => $settings['weight_label'],
            'value' => $weight_value,
        ];
    }

    if ($settings['show_dimensions'] === 'yes' && ($has_dimensions || $is_editor)) {
        if ($settings['dimensions_format'] === 'combined') {
            $dim_parts = [];
            if ($length) {
                $dim_parts[] = number_format((float) $length, 1);
            }
            if ($width) {
                $dim_parts[] = number_format((float) $width, 1);
            }
            if ($height) {
                $dim_parts[] = number_format((float) $height, 1);
            }
            $dim_value = ! empty($dim_parts) ? implode(' × ', $dim_parts) : '—';
            if ($settings['show_units'] === 'yes' && ! empty($dim_parts)) {
                $dim_value .= ' ' . $dimension_unit;
            }
            $attributes[] = [
                'label' => $settings['dimensions_label'],
                'value' => $dim_value,
            ];
        } else {
            // Separate rows
            if ($length || $is_editor) {
                $l_value = $length ? number_format((float) $length, 1) : '—';
                if ($settings['show_units'] === 'yes' && $length) {
                    $l_value .= ' ' . $dimension_unit;
                }
                $attributes[] = [
                    'label' => __('Length', 'ggm-commerce'),
                    'value' => $l_value,
                ];
            }
            if ($width || $is_editor) {
                $w_value = $width ? number_format((float) $width, 1) : '—';
                if ($settings['show_units'] === 'yes' && $width) {
                    $w_value .= ' ' . $dimension_unit;
                }
                $attributes[] = [
                    'label' => __('Width', 'ggm-commerce'),
                    'value' => $w_value,
                ];
            }
            if ($height || $is_editor) {
                $h_value = $height ? number_format((float) $height, 1) : '—';
                if ($settings['show_units'] === 'yes' && $height) {
                    $h_value .= ' ' . $dimension_unit;
                }
                $attributes[] = [
                    'label' => __('Height', 'ggm-commerce'),
                    'value' => $h_value,
                ];
            }
        }
    }

    // Get custom attributes if premium is active and enabled
    $custom_attributes = [];
    $show_custom = isset($settings['show_custom_attributes']) && $settings['show_custom_attributes'] === 'yes';

    if ($show_custom && class_exists('GGM_Commerce_License') && GGM_Commerce_License::is_premium_active()) {
        $product_id = null;
        if ($product_data && isset($product_data->id)) {
            $product_id = $product_data->id;
        }

        if ($product_id && class_exists('GGM_Commerce_Attributes')) {
            $attributes_manager = GGM_Commerce_Attributes::get_instance();
            $formatted_attrs    = $attributes_manager->get_formatted_product_attributes($product_id);

            foreach ($formatted_attrs as $attr) {
                // Only show attributes that have a value
                if (! empty($attr['value'])) {
                    $display_value = $attr['value'];
                    if (! empty($attr['unit']) && $settings['show_units'] === 'yes') {
                        $display_value .= ' ' . $attr['unit'];
                    }
                    $custom_attributes[] = [
                        'label' => $attr['name'],
                        'value' => $display_value,
                    ];
                }
            }
        }

        // In editor mode, show placeholder custom attributes if none exist
        if ($is_editor && empty($custom_attributes)) {
            $custom_attributes[] = [
                'label' => __('Energy Rating', 'ggm-commerce'),
                'value' => 'A++',
            ];
            $custom_attributes[] = [
                'label' => __('Capacity', 'ggm-commerce'),
                'value' => '14 L',
            ];
        }
    }

    // Merge attributes based on position setting
    $position = isset($settings['custom_attributes_position']) ? $settings['custom_attributes_position'] : 'after';
    if ($position === 'before') {
        $attributes = array_merge($custom_attributes, $attributes);
    } else {
        $attributes = array_merge($attributes, $custom_attributes);
    }

    if (empty($attributes)) {
        return;
    }

    // Render based on layout
    echo '<div class="ggmc-product-attributes layout-' . esc_attr($settings['layout']) . '">';

    switch ($settings['layout']) {
        case 'table':
            ggmc_product_attributes_render_table_layout($attributes, $settings);
            break;
        case 'list':
            ggmc_product_attributes_render_list_layout($attributes, $settings);
            break;
        case 'inline':
            ggmc_product_attributes_render_inline_layout($attributes, $settings);
            break;
        case 'grid':
            ggmc_product_attributes_render_grid_layout($attributes, $settings);
            break;
    }

    echo '</div>';
}

/**
 * Render table layout (div-based for consistency).
 *
 * @param array $attributes List of attribute arrays with 'label' and 'value' keys.
 * @param array $settings   Widget settings.
 */
function ggmc_product_attributes_render_table_layout( $attributes, $settings ) {
    echo '<div class="ggmc-attr-list">';
    foreach ($attributes as $attr) {
        echo '<div class="ggmc-attr-row">';
        if ($settings['show_labels'] === 'yes') {
            echo '<span class="attribute-label">' . esc_html($attr['label']) . '</span>';
        }
        echo '<span class="attribute-value">' . esc_html($attr['value']) . '</span>';
        echo '</div>';
    }
    echo '</div>';
}

/**
 * Render list layout (div-based for consistency).
 *
 * @param array $attributes List of attribute arrays with 'label' and 'value' keys.
 * @param array $settings   Widget settings.
 */
function ggmc_product_attributes_render_list_layout( $attributes, $settings ) {
    echo '<div class="ggmc-attr-list">';
    foreach ($attributes as $attr) {
        echo '<div class="ggmc-attr-row">';
        if ($settings['show_labels'] === 'yes') {
            echo '<span class="attribute-label">' . esc_html($attr['label']) . ':</span> ';
        }
        echo '<span class="attribute-value">' . esc_html($attr['value']) . '</span>';
        echo '</div>';
    }
    echo '</div>';
}

/**
 * Render inline layout.
 *
 * @param array $attributes List of attribute arrays with 'label' and 'value' keys.
 * @param array $settings   Widget settings.
 */
function ggmc_product_attributes_render_inline_layout( $attributes, $settings ) {
    echo '<div class="ggmc-attr-inline">';
    $items = [];
    foreach ($attributes as $attr) {
        $item = '';
        if ($settings['show_labels'] === 'yes') {
            $item .= '<span class="attribute-label">' . esc_html($attr['label']) . ':</span> ';
        }
        $item  .= '<span class="attribute-value">' . esc_html($attr['value']) . '</span>';
        $items[] = '<span class="ggmc-attr-item">' . $item . '</span>';
    }
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Items are escaped individually above
    echo implode(' <span class="separator">|</span> ', $items);
    echo '</div>';
}

/**
 * Render grid layout.
 *
 * @param array $attributes List of attribute arrays with 'label' and 'value' keys.
 * @param array $settings   Widget settings.
 */
function ggmc_product_attributes_render_grid_layout( $attributes, $settings ) {
    echo '<div class="ggmc-attr-grid">';
    foreach ($attributes as $attr) {
        echo '<div class="ggmc-attr-item">';
        if ($settings['show_labels'] === 'yes') {
            echo '<div class="attribute-label">' . esc_html($attr['label']) . '</div>';
        }
        echo '<div class="attribute-value">' . esc_html($attr['value']) . '</div>';
        echo '</div>';
    }
    echo '</div>';
}
