<?php
defined( 'ABSPATH' ) || exit;

class PIPEBU_Color {

    // -------------------------------------------------------------------------
    // Ensure the global pa_color attribute taxonomy exists. Returns attribute ID.
    // -------------------------------------------------------------------------

    public static function get_or_create_color_attribute(): int {
        $taxonomy = wc_attribute_taxonomy_name( 'color' ); // WooCommerce standard: pa_color
        $id = wc_attribute_taxonomy_id_by_name( $taxonomy );
        if ( $id ) {
            return $id;
        }

        $id = wc_create_attribute( [
            'name'         => 'Color',
            'slug'         => 'color',
            'type'         => 'select',
            'order_by'     => 'menu_order',
            'has_archives' => false,
        ] );

        if ( is_wp_error( $id ) ) {
            return 0;
        }

        // Register taxonomy so it's available in this request without a reload.
        if ( ! taxonomy_exists( $taxonomy ) ) {
            register_taxonomy( $taxonomy, 'product', [] );
        }

        return (int) $id;
    }

    // -------------------------------------------------------------------------
    // Find or create a pa_color term. Returns [ 'id' => int, 'slug' => string ].
    // -------------------------------------------------------------------------

    public static function ensure_color_term( string $name ): array {
        $taxonomy = wc_attribute_taxonomy_name( 'color' ); // WooCommerce standard: pa_color

        if ( ! taxonomy_exists( $taxonomy ) ) {
            register_taxonomy( $taxonomy, 'product', [] );
        }

        $term = get_term_by( 'name', $name, $taxonomy );
        if ( $term ) {
            return [ 'id' => $term->term_id, 'slug' => $term->slug ];
        }

        $result = wp_insert_term( $name, $taxonomy );
        if ( is_wp_error( $result ) ) {
            return [ 'id' => 0, 'slug' => sanitize_title( $name ) ];
        }

        $term = get_term( $result['term_id'], $taxonomy );
        return [
            'id'   => $term ? $term->term_id : $result['term_id'],
            'slug' => $term ? $term->slug    : sanitize_title( $name ),
        ];
    }

    // -------------------------------------------------------------------------
    // Set pa_color attribute on parent variable product + create one variation
    // per color. Expects $product_id already saved.
    //
    // $colors: [ ['name' => '', 'price' => '', 'attachment_id' => 0], … ]
    // -------------------------------------------------------------------------

    public static function create_variations( int $product_id, array $colors ): void {
        if ( empty( $colors ) ) {
            return;
        }

        $attr_id = self::get_or_create_color_attribute();
        if ( ! $attr_id ) {
            return;
        }

        // Collect term data and build options lists.
        $term_ids   = [];
        $term_map   = []; // name → [ 'id', 'slug' ]

        foreach ( $colors as $color ) {
            $name = sanitize_text_field( $color['name'] ?? '' );
            if ( ! $name ) {
                continue;
            }
            $term_data          = self::ensure_color_term( $name );
            $term_ids[]         = $term_data['id'];
            $term_map[ $name ]  = $term_data;
        }

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

        // Set attribute on parent product (term IDs, variation=true).
        $product = wc_get_product( $product_id );
        if ( ! $product ) {
            return;
        }

        $attribute = new WC_Product_Attribute();
        $attribute->set_id( $attr_id );
        $attribute->set_name( wc_attribute_taxonomy_name( 'color' ) );
        $attribute->set_options( $term_ids );
        $attribute->set_position( 0 );
        $attribute->set_visible( true );
        $attribute->set_variation( true );
        $product->set_attributes( [ $attribute ] );
        $product->save();

        // Create one variation per color.
        foreach ( $colors as $color ) {
            $name   = sanitize_text_field( $color['name']          ?? '' );
            $price  = sanitize_text_field( $color['price']         ?? '' );
            $att_id = absint(              $color['attachment_id']  ?? 0 );

            if ( ! $name || ! isset( $term_map[ $name ] ) ) {
                continue;
            }

            $slug = $term_map[ $name ]['slug'];

            $variation = new WC_Product_Variation();
            $variation->set_parent_id( $product_id );
            $variation->set_attributes( [ wc_attribute_taxonomy_name( 'color' ) => $slug ] );

            if ( $price !== '' ) {
                $variation->set_regular_price( wc_format_decimal( $price ) );
            }
            if ( $att_id ) {
                $variation->set_image_id( $att_id );
            }
            $variation->set_status( 'publish' );
            $variation->save();
        }

        // Sync min/max prices on parent.
        WC_Product_Variable::sync( $product_id );
    }
}
