<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Module_Products extends SBPAI_Module_Base {

    public function generate() {
        if ( ! class_exists( 'WooCommerce' ) ) return false;

        $type      = isset( $this->args['wc_type'] ) ? $this->args['wc_type'] : 'simple';
        $source    = isset( $this->args['source'] ) ? $this->args['source'] : 'hybrid';
        $price_min = isset( $this->args['price_min'] ) ? intval($this->args['price_min']) : 10;
        $price_max = isset( $this->args['price_max'] ) ? intval($this->args['price_max']) : 500;
        $stock     = isset( $this->args['stock'] ) ? $this->args['stock'] : 'random';
        $use_image = isset( $this->args['image'] ) ? intval($this->args['image']) : 1;
        $use_terms = isset( $this->args['terms'] ) ? intval($this->args['terms']) : 1;
        $reviews   = isset( $this->args['reviews'] ) ? intval($this->args['reviews']) : 1;

        // Content Engine
        if ( $source === 'ai' ) {
            $name  = SBPAI_Service_AI::generate_text( 'Generate a realistic WooCommerce product name' );
            $desc  = SBPAI_Service_AI::generate_text( 'Generate a detailed eCommerce product description with features and benefits.' );
            $short = SBPAI_Service_AI::generate_text( 'Generate a brief 2-sentence product short description.' );
        } elseif ( $source === 'faker' ) {
            $name  = ucwords( $this->faker->words( wp_rand( 2, 4 ), true ) );
            $desc  = $this->faker->paragraphs( wp_rand( 2, 4 ), true );
            $short = $this->faker->sentence(10);
        } else {
            $name  = SBPAI_Service_AI::generate_text( 'Generate a realistic WooCommerce product name' );
            $desc  = $this->faker->paragraphs( wp_rand( 2, 4 ), true );
            $short = $this->faker->sentence(10);
        }

        $product = $this->create_core_product($type, $name, $desc, $short, $price_min, $price_max, $stock);

        if ( $product ) {
            $product_id = $product->get_id();
            
            update_post_meta( $product_id, '_sbpai_product', '1' );

            if ( $use_terms ) {
                $this->assign_terms( $product_id );
            }

            if ( $use_image ) {
                $img_keyword = get_option('sbpai_active_niche', 'General');
                $img = SBPAI_Service_Media::fetch_image( 800, 800, $img_keyword );
                if ( $img ) {
                    $product->set_image_id( $img );
                    $product->save();
                }
            }

            if ( $reviews ) {
                $this->generate_reviews( $product_id );
            }

            // Secondary background triggers based on checkboxes
            if ( isset($this->args['orders']) && intval($this->args['orders']) === 1 ) {
                $this->spawn_related_order( $product_id );
            }
            if ( isset($this->args['coupons']) && intval($this->args['coupons']) === 1 ) {
                $this->spawn_related_coupon( $product_id );
            }

            return $product_id;
        }

        return false;
    }

    private function create_core_product( $type, $name, $desc, $short, $p_min, $p_max, $stock ) {
        if ( $type === 'variable' ) {
            $product = new WC_Product_Variable();
        } elseif ( $type === 'grouped' ) {
            $product = new WC_Product_Grouped();
        } else {
            $product = new WC_Product_Simple();
        }

        if ( $type === 'virtual' ) {
            $product->set_virtual( true );
            $product->set_downloadable( true );
        }

        $product->set_name( $name );
        $product->set_description( $desc );
        $product->set_short_description( $short );
        $product->set_status( 'publish' );
        
        $calc_stock = 'instock';
        if ( $stock === 'outofstock' ) {
            $calc_stock = 'outofstock';
        } elseif ( $stock === 'random' ) {
            $calc_stock = ( wp_rand( 1, 10 ) > 2 ) ? 'instock' : 'outofstock';
            if ( $calc_stock === 'instock' ) {
                $product->set_manage_stock( true );
                $product->set_stock_quantity( wp_rand( 5, 100 ) );
            }
        }
        $product->set_stock_status( $calc_stock );

        if ( $type === 'simple' ) {
            $price = wp_rand( $p_min, $p_max );
            $product->set_regular_price( $price );
            if ( wp_rand( 1, 4 ) === 1 ) {
                $product->set_sale_price( $price * 0.8 ); // 20% off
            }
        }

        $product_id = $product->save();

        // Handle structural complexity
        if ( $type === 'variable' ) {
            $this->build_variations( $product_id, $p_min, $p_max, $stock );
        } elseif ( $type === 'grouped' ) {
            $this->build_grouped_children( $product_id );
        }

        return $product;
    }

    private function build_variations( $product_id, $p_min, $p_max, $stock ) {
        $attribute_pools = array(
            'pa_size'    => array( 'XS', 'S', 'M', 'L', 'XL', 'XXL' ),
            'pa_color'   => array( 'Red', 'Blue', 'Black', 'White', 'Green', 'Yellow' ),
            'pa_material'=> array( 'Cotton', 'Polyester', 'Wool', 'Silk', 'Linen' ),
        );

        // Pick one random attribute pool
        $attr_keys     = array_keys( $attribute_pools );
        $selected_attr = $attr_keys[ wp_rand( 0, count( $attr_keys ) - 1 ) ];
        $all_terms     = $attribute_pools[ $selected_attr ];

        // Use only 3 random terms so we don't bloat
        shuffle( $all_terms );
        $terms = array_slice( $all_terms, 0, 3 );

        // Register taxonomy if not already present (WC does this on install, but just in case)
        if ( ! taxonomy_exists( $selected_attr ) ) {
            register_taxonomy( $selected_attr, 'product' );
        }

        // Ensure each term exists in the taxonomy
        $term_slugs = array();
        foreach ( $terms as $term_name ) {
            if ( ! term_exists( $term_name, $selected_attr ) ) {
                wp_insert_term( $term_name, $selected_attr );
            }
            $term_obj = get_term_by( 'name', $term_name, $selected_attr );
            if ( $term_obj ) {
                $term_slugs[] = $term_obj->slug;
                wp_set_object_terms( $product_id, $term_obj->term_id, $selected_attr, true );
            }
        }

        // Build a WC_Product_Attribute object — this is the correct modern API
        $attribute = new WC_Product_Attribute();
        $attribute->set_id( wc_attribute_taxonomy_id_by_name( $selected_attr ) );
        $attribute->set_name( $selected_attr );
        $attribute->set_options( $term_slugs );
        $attribute->set_position( 0 );
        $attribute->set_visible( true );
        $attribute->set_variation( true );

        // Load the parent product and attach the attribute properly
        $parent = wc_get_product( $product_id );
        if ( ! $parent ) return;

        $parent->set_attributes( array( $attribute ) );
        $parent->save();

        // Generate one variation per selected term
        foreach ( $term_slugs as $term_slug ) {
            $variation = new WC_Product_Variation();
            $variation->set_parent_id( $product_id );
            $variation->set_attributes( array( $selected_attr => $term_slug ) );
            $variation->set_regular_price( wp_rand( $p_min, $p_max ) );
            if ( wp_rand( 1, 3 ) === 1 ) {
                $variation->set_sale_price( round( wp_rand( $p_min, $p_max ) * 0.8 ) );
            }
            
            $calc_stock = 'instock';
            if ( $stock === 'outofstock' ) {
                $calc_stock = 'outofstock';
                $variation->set_manage_stock( false );
            } elseif ( $stock === 'random' ) {
                $calc_stock = ( wp_rand( 1, 10 ) > 2 ) ? 'instock' : 'outofstock';
                if ( $calc_stock === 'instock' ) {
                    $variation->set_manage_stock( true );
                    $variation->set_stock_quantity( wp_rand( 5, 100 ) );
                } else {
                    $variation->set_manage_stock( false );
                }
            } else {
                $variation->set_manage_stock( true );
                $variation->set_stock_quantity( wp_rand( 5, 100 ) );
            }
            
            $variation->set_stock_status( $calc_stock );
            $variation->set_status( 'publish' );
            $variation_id = $variation->save();
            update_post_meta( $variation_id, '_sbpai_product', '1' );
        }

        // Sync variation price cache so WC shows the price range
        WC_Product_Variable::sync( $product_id );
    }

    private function build_grouped_children( $product_id ) {
        $children = array();
        for ( $i = 0; $i < wp_rand( 2, 4 ); $i++ ) {
            $child = new WC_Product_Simple();
            $child->set_name( 'Grouped Part ' . ucfirst( $this->faker->word ) );
            $child->set_regular_price( wp_rand( 10, 50 ) );
            $child->set_status( 'publish' );
            $child_id = $child->save();
            update_post_meta( $child_id, '_sbpai_product', '1' );
            $children[] = $child_id;
        }
        $parent = wc_get_product( $product_id );
        if ( $parent ) {
            $parent->set_children( $children );
            $parent->save();
        }
    }

    private function assign_terms( $product_id ) {
        $cat_taxonomy = 'product_cat';
        $tag_taxonomy = 'product_tag';

        $cats = get_terms( array( 'taxonomy' => $cat_taxonomy, 'hide_empty' => false ) );
        if ( empty( $cats ) ) {
            $bases = array('Electronics', 'Fashion', 'Fitness', 'Home', 'Services');
            foreach ( $bases as $b ) {
                wp_insert_term( sanitize_text_field( $b ), $cat_taxonomy );
            }
            $cats = get_terms( array( 'taxonomy' => $cat_taxonomy, 'hide_empty' => false ) );
        }
        
        if ( !empty($cats) ) {
            shuffle( $cats );
            wp_set_object_terms( $product_id, $cats[0]->term_id, $cat_taxonomy );
        }

        $tag = ucfirst( $this->faker->word );
        wp_insert_term( $tag, $tag_taxonomy );
        wp_set_object_terms( $product_id, $tag, $tag_taxonomy, true );
    }

    private function generate_reviews( $product_id ) {
        $count = wp_rand( 1, 3 );
        for ( $i = 0; $i < $count; $i++ ) {
            $time = current_time('mysql');
            $comment_id = wp_insert_comment( array(
                'comment_post_ID'      => $product_id,
                'comment_author'       => $this->faker->name,
                'comment_author_email' => $this->faker->email,
                'comment_content'      => $this->faker->sentence(12),
                'comment_type'         => 'review',
                'comment_date'         => $time,
                'comment_approved'     => 1,
            ) );
            if ( $comment_id ) {
                update_comment_meta( $comment_id, 'rating', wp_rand( 3, 5 ) );
            }
        }
    }

    // Advanced Linking Operations
    private function spawn_related_order( $product_id ) {
        if ( class_exists('SBPAI_Action_Scheduler') ) {
            $scheduler = new SBPAI_Action_Scheduler();
            // Spawns 1 specialized order requesting THIS specific product logic
            $scheduler->schedule_job('orders', 1, get_option('sbpai_active_niche'), get_option('sbpai_active_ai'), ['force_product_id' => $product_id]);
        }
    }

    private function spawn_related_coupon( $product_id ) {
        if ( class_exists('SBPAI_Action_Scheduler') ) {
            $scheduler = new SBPAI_Action_Scheduler();
            // Spawns 1 general coupon
            $scheduler->schedule_job('coupons', 1, get_option('sbpai_active_niche'), get_option('sbpai_active_ai'), []);
        }
    }
}
