<?php

/**
 * Panel Renderer - Renders the product swatches data panel.
 *
 * @package B3WVS\VariationSwatches\Admin\ProductSwatches
 */
namespace B3WVS\VariationSwatches\Admin\ProductSwatches;

defined( 'ABSPATH' ) || exit;
/**
 * PanelRenderer Class
 *
 * Handles the rendering of the WooCommerce product data panel for swatch overrides.
 */
class PanelRenderer {
    /**
     * Meta key for product overrides.
     *
     * @var string
     */
    private $meta_key;

    /**
     * Constructor.
     *
     * @param string $meta_key Meta key for overrides.
     */
    public function __construct( $meta_key ) {
        $this->meta_key = $meta_key;
    }

    /**
     * Render the product data panel.
     */
    public function render() {
        global $post;
        if ( !$post instanceof \WP_Post ) {
            return;
        }
        $product = wc_get_product( $post->ID );
        $this->render_panel_content( $product, $post->ID );
    }

    /**
     * Render the panel for a specific product (used by AJAX refresh).
     *
     * @param \WC_Product $product Product object.
     */
    public function render_for_product( $product ) {
        if ( !$product || !method_exists( $product, 'get_id' ) ) {
            return;
        }
        $this->render_panel_content( $product, $product->get_id() );
    }

    /**
     * Render the panel content.
     *
     * @param \WC_Product|null $product  Product object.
     * @param int              $post_id  Product/post ID.
     */
    private function render_panel_content( $product, $post_id ) {
        if ( !$product || !$product->is_type( 'variable' ) ) {
            return;
        }
        $variation_attributes = $this->get_all_attribute_options( $product );
        $overrides = get_post_meta( $post_id, $this->meta_key, true );
        if ( !is_array( $overrides ) ) {
            $overrides = array();
        }
        wp_nonce_field( 'b3wvs_save_product_swatches', 'b3wvs_product_swatches_nonce' );
        echo '<div id="b3wvs_swatches_panel" class="panel woocommerce_options_panel wc-metaboxes-wrapper hidden">';
        echo '<div class="options_group">';
        echo '<p class="form-field">' . esc_html__( 'Manage swatch display per option. Custom attributes save per product; global attributes update the shared attribute term.', 'b3-swatches' ) . '</p>';
        if ( empty( $variation_attributes ) ) {
            echo '<p class="form-field">' . esc_html__( 'No variation attributes found.', 'b3-swatches' ) . '</p>';
            echo '</div></div>';
            return;
        }
        echo '<div class="wc-metaboxes b3-wvs-product-metaboxes">';
        foreach ( $variation_attributes as $attribute_name => $options ) {
            $this->render_attribute_metabox( $attribute_name, $options, $overrides );
        }
        echo '</div>';
        // End wc-metaboxes.
        echo '</div></div>';
    }

    /**
     * Render a single attribute metabox.
     *
     * @param string $attribute_name Attribute name.
     * @param array  $options        Attribute options.
     * @param array  $overrides      Saved overrides.
     */
    private function render_attribute_metabox( $attribute_name, $options, $overrides ) {
        $label = wc_attribute_label( $attribute_name );
        $is_taxonomy = taxonomy_exists( $attribute_name );
        echo '<div class="wc-metabox closed b3-wvs-attribute-metabox" data-attribute="' . esc_attr( $attribute_name ) . '">';
        echo '<h3 class="b3-wvs-attribute-metabox-title">';
        echo '<strong class="attribute-label">' . esc_html( $label ) . '</strong>';
        echo '<span class="b3-wvs-handlediv" aria-hidden="true"></span>';
        echo '</h3>';
        echo '<div class="wc-metabox-content b3-wvs-attribute-metabox-content" style="display:none;">';
        echo '<div class="b3-wvs-order-hint">';
        echo '<div class="b3-wvs-order-hint-title">' . esc_html__( 'Drag to reorder swatches', 'b3-swatches' ) . '</div>';
        echo '<div class="b3-wvs-order-hint-body">';
        echo '<span>' . esc_html__( 'Top entry = left-most swatch', 'b3-swatches' ) . '</span>';
        echo '<span aria-hidden="true" class="b3-wvs-order-hint-arrow">→</span>';
        echo '<span>' . esc_html__( 'Bottom entry = right-most swatch', 'b3-swatches' ) . '</span>';
        echo '</div>';
        echo '<div class="b3-wvs-order-hint-diagram" aria-hidden="true">';
        echo '<span class="b3-wvs-order-hint-chip">1</span>';
        echo '<span class="b3-wvs-order-hint-chip">2</span>';
        echo '<span class="b3-wvs-order-hint-chip">3</span>';
        echo '<span class="b3-wvs-order-hint-arrow">→</span>';
        echo '<span class="b3-wvs-order-hint-chip">…</span>';
        echo '</div>';
        echo '</div>';
        foreach ( $options as $slug ) {
            $this->render_option_row(
                $attribute_name,
                $slug,
                $overrides,
                $is_taxonomy
            );
        }
        echo '</div>';
        // End wc-metabox-content.
        echo '</div>';
        // End wc-metabox.
    }

    /**
     * Render a single option row.
     *
     * @param string $attribute_name Attribute name.
     * @param string $slug           Option slug.
     * @param array  $overrides      Saved overrides.
     * @param bool   $is_taxonomy    Whether the attribute is taxonomy-backed.
     */
    private function render_option_row(
        $attribute_name,
        $slug,
        $overrides,
        $is_taxonomy
    ) {
        $term_label = $slug;
        $term = null;
        if ( $is_taxonomy ) {
            $term = get_term_by( 'slug', $slug, $attribute_name );
            if ( $term && !is_wp_error( $term ) ) {
                $term_label = $term->name;
            }
        }
        $current = array();
        if ( $is_taxonomy && $term && !is_wp_error( $term ) ) {
            $current = array(
                'type'  => (string) get_term_meta( $term->term_id, 'b3_wvs_type', true ),
                'color' => (string) get_term_meta( $term->term_id, 'b3_wvs_color', true ),
                'label' => (string) get_term_meta( $term->term_id, 'b3_wvs_label', true ),
            );
        } elseif ( isset( $overrides[$attribute_name][$slug] ) && is_array( $overrides[$attribute_name][$slug] ) ) {
            $current = $overrides[$attribute_name][$slug];
        }
        $type = ( isset( $current['type'] ) ? $current['type'] : '' );
        $color = ( isset( $current['color'] ) ? $current['color'] : '' );
        $custom_label = ( isset( $current['label'] ) ? $current['label'] : '' );
        $use_color = !empty( $current['use_color'] ) || 'button' === $type && '' !== trim( $color );
        $name_base = ( $is_taxonomy ? 'b3wvs_global_terms[' . esc_attr( $attribute_name ) . '][' . esc_attr( $slug ) . ']' : 'b3wvs_overrides[' . esc_attr( $attribute_name ) . '][' . esc_attr( $slug ) . ']' );
        echo '<div class="b3-wvs-row' . (( $is_taxonomy ? ' b3-wvs-row-global' : '' )) . '" data-attribute="' . esc_attr( $attribute_name ) . '" data-slug="' . esc_attr( $slug ) . '" data-global="' . (( $is_taxonomy ? '1' : '0' )) . '">';
        $this->render_term_column( $term_label, $slug, $is_taxonomy );
        $this->render_fields_column(
            $name_base,
            $term_label,
            $type,
            $custom_label,
            $use_color,
            $color,
            $is_taxonomy,
            $current,
            $term
        );
        $this->render_options_column( $name_base, $current, $is_taxonomy );
        echo '</div>';
        // End row.
    }

    /**
     * Render term info column.
     *
     * @param string $term_label Term label.
     * @param string $slug       Term slug.
     * @param bool   $is_taxonomy Whether the attribute is taxonomy-backed.
     */
    private function render_term_column( $term_label, $slug, $is_taxonomy ) {
        echo '<div class="b3-wvs-col-term">';
        echo '<div class="b3-wvs-term-header">';
        echo '<span class="b3-wvs-drag-handle" role="button" tabindex="0" aria-label="' . esc_attr__( 'Drag to reorder', 'b3-swatches' ) . '"><span class="dashicons dashicons-move"></span></span>';
        echo '<label>' . esc_html__( 'Option', 'b3-swatches' ) . '</label>';
        if ( $is_taxonomy ) {
            echo '<span class="b3-wvs-global-badge">' . esc_html__( 'Global attribute', 'b3-swatches' ) . '</span>';
        }
        echo '</div>';
        echo '<div class="b3-wvs-term-info">';
        echo '<span class="b3-wvs-term-name">' . esc_html( $term_label ) . '</span>';
        echo '<code class="b3-wvs-term-slug">' . esc_html( $slug ) . '</code>';
        if ( $is_taxonomy ) {
            echo '<div class="b3-wvs-global-note">' . esc_html__( 'Edits here update the global attribute term and apply to every product. For button swatches, you can set a custom label here and the button color is optional.', 'b3-swatches' ) . '</div>';
        }
        echo '</div>';
        echo '</div>';
    }

    /**
     * Get all attribute options for a product.
     *
     * Unlike get_variation_attributes() which only returns options used by variations,
     * this returns all options defined on the product's attributes. This ensures
     * copied swatch overrides are visible even before variations are created.
     *
     * @param \WC_Product $product Product.
     * @return array attribute_name => options array.
     */
    private function get_all_attribute_options( $product ) {
        $attributes = $product->get_attributes();
        $result = array();
        if ( !is_array( $attributes ) ) {
            return $result;
        }
        foreach ( $attributes as $attribute ) {
            if ( !is_object( $attribute ) || !method_exists( $attribute, 'get_name' ) ) {
                continue;
            }
            // Only include variation attributes.
            if ( method_exists( $attribute, 'get_variation' ) && !$attribute->get_variation() ) {
                continue;
            }
            $name = $attribute->get_name();
            $options = array();
            if ( method_exists( $attribute, 'is_taxonomy' ) && $attribute->is_taxonomy() ) {
                // Taxonomy attribute - get term slugs.
                $term_ids = ( method_exists( $attribute, 'get_options' ) ? $attribute->get_options() : array() );
                foreach ( $term_ids as $term_id ) {
                    $term = get_term( $term_id );
                    if ( $term && !is_wp_error( $term ) ) {
                        $options[] = $term->slug;
                    }
                }
            } else {
                // Custom attribute - options are already slugs/values.
                $options = ( method_exists( $attribute, 'get_options' ) ? $attribute->get_options() : array() );
            }
            if ( !empty( $options ) ) {
                $result[$name] = $options;
            }
        }
        return $result;
    }

    /**
     * Render fields container column.
     *
     * @param string $name_base    Form field name base.
     * @param string $term_label   Term label for placeholder.
     * @param string $type         Swatch type.
     * @param string $custom_label Custom label.
     * @param bool   $use_color    Use color toggle.
     * @param string $color        Primary color.
     * @param bool   $is_taxonomy  Whether the attribute is taxonomy-backed.
     * @param array  $current      Current row values.
     * @param object $term         Term object when taxonomy-backed.
     */
    private function render_fields_column(
        $name_base,
        $term_label,
        $type,
        $custom_label,
        $use_color,
        $color,
        $is_taxonomy,
        $current,
        $term
    ) {
        $default_color_label = __( 'Color', 'b3-swatches' );
        $button_color_label = ( $is_taxonomy ? __( 'Button Color (optional)', 'b3-swatches' ) : __( 'Button Color', 'b3-swatches' ) );
        echo '<div class="b3-wvs-col-fields">';
        echo '<div class="b3-wvs-col-type b3-wvs-field-group">';
        echo '<label>' . esc_html__( 'Type', 'b3-swatches' ) . '</label>';
        echo '<div class="b3-wvs-controls">';
        echo '<select class="b3-wvs-swatch-type" name="' . esc_attr( $name_base . '[type]' ) . '">';
        echo '<option value="">' . esc_html__( 'Default', 'b3-swatches' ) . '</option>';
        echo '<option value="button" ' . selected( $type, 'button', false ) . '>' . esc_html__( 'Button/Label', 'b3-swatches' ) . '</option>';
        echo '<option value="color" ' . selected( $type, 'color', false ) . '>' . esc_html__( 'Color', 'b3-swatches' ) . '</option>';
        echo '</select>';
        echo '</div>';
        echo '</div>';
        // Label.
        echo '<div class="b3-wvs-col-label b3-wvs-field-group">';
        echo '<label>' . esc_html__( 'Label Text', 'b3-swatches' ) . '</label>';
        echo '<div class="b3-wvs-controls">';
        echo '<input type="text" name="' . esc_attr( $name_base . '[label]' ) . '" value="' . esc_attr( $custom_label ) . '" placeholder="' . esc_attr( $term_label ) . '" />';
        if ( !$is_taxonomy ) {
            echo '<input type="checkbox" class="b3-wvs-use-color" name="' . esc_attr( $name_base . '[use_color]' ) . '" value="1" ' . checked( $use_color, true, false ) . ' style="display:none;" />';
            echo '<button type="button" class="button b3-wvs-toggle-color" aria-expanded="' . (( $use_color ? 'true' : 'false' )) . '">' . (( $use_color ? esc_html__( 'Remove color', 'b3-swatches' ) : esc_html__( 'Add color', 'b3-swatches' ) )) . '</button>';
        }
        echo '</div>';
        echo '</div>';
        // Color Picker.
        echo '<div class="b3-wvs-col-color b3-wvs-field-group" data-label-default="' . esc_attr( $default_color_label ) . '" data-label-button="' . esc_attr( $button_color_label ) . '">';
        echo '<label>' . esc_html( $default_color_label ) . '</label>';
        echo '<div class="b3-wvs-color-control">';
        echo '<input type="text" class="b3-wvs-color-picker b3-wvs-color-picker-primary" name="' . esc_attr( $name_base . '[color]' ) . '" value="' . esc_attr( $color ) . '" />';
        echo ' <button type="button" class="button b3-wvs-eyedropper" data-target="primary" aria-label="' . esc_attr__( 'Pick color', 'b3-swatches' ) . '"><span class="dashicons dashicons-color-picker"></span></button>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        // End fields container.
    }

    /**
     * Render options column.
     *
     * @param string $name_base   Form field name base.
     * @param array  $current     Current row values.
     * @param bool   $is_taxonomy Whether the attribute is taxonomy-backed.
     */
    private function render_options_column( $name_base, $current, $is_taxonomy ) {
    }

}
