<?php
/**
 * Technical Specifications Extractor
 *
 * Extracts technical specifications from content.
 *
 * @package BoostBot
 * @since   1.0.0
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class BoostBot_Specs_Extractor
 *
 * Extracts technical specs from page content, tables, and WooCommerce products.
 */
class BoostBot_Specs_Extractor {

    /**
     * Common spec patterns (Hebrew + English).
     *
     * @var array
     */
    private $spec_patterns = array(
        // Hebrew patterns.
        'dimensions'  => '/(?:מידות|גודל|אורך|רוחב|גובה|עומק)[\s:]+([0-9.,×xX\s]+(?:ס"מ|מ"מ|מטר|סמ|מ\')?)/u',
        'weight'      => '/(?:משקל)[\s:]+([0-9.,]+\s*(?:ק"ג|גרם|טון|kg|g))/u',
        'capacity'    => '/(?:קיבולת|נפח)[\s:]+([0-9.,]+\s*(?:ליטר|מ"ל|ml|L))/u',
        'power'       => '/(?:הספק|עוצמה)[\s:]+([0-9.,]+\s*(?:וואט|קילווואט|W|kW|HP))/u',
        'material'    => '/(?:חומר|עשוי מ|מיוצר מ)[\s:]+([^\n,\.]+)/u',
        'color'       => '/(?:צבע|צבעים)[\s:]+([^\n,\.]+)/u',
        'warranty'    => '/(?:אחריות)[\s:]+([^\n,\.]+)/u',
        'model'       => '/(?:דגם|מק"ט|SKU)[\s:]+([^\n,\.]+)/u',
        'brand'       => '/(?:מותג|יצרן)[\s:]+([^\n,\.]+)/u',
        'voltage'     => '/(?:מתח|וולט)[\s:]+([0-9.,]+\s*(?:וולט|V))/u',
        'frequency'   => '/(?:תדירות|תדר)[\s:]+([0-9.,]+\s*(?:הרץ|Hz|MHz|GHz))/u',
        'speed'       => '/(?:מהירות)[\s:]+([0-9.,]+\s*(?:סל"ד|RPM|קמ"ש|km\/h))/u',

        // English patterns.
        'dimensions_en' => '/(?:dimensions?|size|length|width|height)[\s:]+([0-9.,×xX\s]+(?:cm|mm|m|in|")?)/i',
        'weight_en'     => '/(?:weight)[\s:]+([0-9.,]+\s*(?:kg|g|lbs?|oz))/i',
        'capacity_en'   => '/(?:capacity|volume)[\s:]+([0-9.,]+\s*(?:L|ml|gal))/i',
        'power_en'      => '/(?:power|wattage)[\s:]+([0-9.,]+\s*(?:W|kW|HP))/i',
        'material_en'   => '/(?:material|made of)[\s:]+([^\n,\.]+)/i',
    );

    /**
     * Extract specs from content.
     *
     * @param string $content   Content to parse.
     * @param string $post_type Post type.
     * @param int    $post_id   Optional post ID for WooCommerce.
     * @return array Extracted specs.
     */
    public function extract( string $content, string $post_type = 'page', int $post_id = 0 ): array {
        $specs = array();

        // Extract using patterns.
        foreach ( $this->spec_patterns as $key => $pattern ) {
            if ( preg_match( $pattern, $content, $matches ) ) {
                $clean_key         = preg_replace( '/_en$/', '', $key );
                $specs[ $clean_key ] = trim( $matches[1] );
            }
        }

        // Extract from WooCommerce product attributes.
        if ( 'product' === $post_type && $post_id > 0 && class_exists( 'WooCommerce' ) ) {
            $wc_specs = $this->extract_woocommerce_specs( $post_id );
            $specs    = array_merge( $specs, $wc_specs );
        }

        // Extract from tables (common for specs).
        $table_specs = $this->extract_from_tables( $content );
        $specs       = array_merge( $table_specs, $specs ); // Pattern specs override tables.

        // Extract from definition lists.
        $dl_specs = $this->extract_from_definition_lists( $content );
        $specs    = array_merge( $dl_specs, $specs );

        return $specs;
    }

    /**
     * Extract specs from HTML tables.
     *
     * @param string $content HTML content.
     * @return array Extracted specs.
     */
    private function extract_from_tables( string $content ): array {
        $specs = array();

        // Find tables.
        if ( preg_match_all( '/<table[^>]*>(.*?)<\/table>/is', $content, $tables ) ) {
            foreach ( $tables[1] as $table ) {
                // Find rows.
                if ( preg_match_all( '/<tr[^>]*>(.*?)<\/tr>/is', $table, $rows ) ) {
                    foreach ( $rows[1] as $row ) {
                        // Find cells.
                        if ( preg_match_all( '/<t[dh][^>]*>(.*?)<\/t[dh]>/is', $row, $cells ) ) {
                            if ( count( $cells[1] ) >= 2 ) {
                                $key   = $this->clean_cell( $cells[1][0] );
                                $value = $this->clean_cell( $cells[1][1] );

                                // Only add if key is short (spec name) and both have values.
                                if ( $key && $value && mb_strlen( $key ) < 50 && mb_strlen( $value ) < 500 ) {
                                    $specs[ $key ] = $value;
                                }
                            }
                        }
                    }
                }
            }
        }

        return $specs;
    }

    /**
     * Extract from definition lists.
     *
     * @param string $content HTML content.
     * @return array Extracted specs.
     */
    private function extract_from_definition_lists( string $content ): array {
        $specs = array();

        // Find <dt>/<dd> pairs.
        if ( preg_match_all( '/<dt[^>]*>(.*?)<\/dt>\s*<dd[^>]*>(.*?)<\/dd>/is', $content, $matches, PREG_SET_ORDER ) ) {
            foreach ( $matches as $match ) {
                $key   = $this->clean_cell( $match[1] );
                $value = $this->clean_cell( $match[2] );

                if ( $key && $value ) {
                    $specs[ $key ] = $value;
                }
            }
        }

        return $specs;
    }

    /**
     * Extract WooCommerce product attributes.
     *
     * @param int $post_id Product ID.
     * @return array Product specs.
     */
    private function extract_woocommerce_specs( int $post_id ): array {
        $specs = array();

        if ( ! function_exists( 'wc_get_product' ) ) {
            return $specs;
        }

        $product = wc_get_product( $post_id );

        if ( ! $product ) {
            return $specs;
        }

        // Get attributes.
        $attributes = $product->get_attributes();

        foreach ( $attributes as $attr ) {
            if ( is_a( $attr, 'WC_Product_Attribute' ) ) {
                $name    = wc_attribute_label( $attr->get_name() );
                $options = $attr->get_options();

                if ( ! empty( $options ) ) {
                    // For taxonomy attributes, get term names.
                    if ( $attr->is_taxonomy() ) {
                        $term_names = array();
                        foreach ( $options as $term_id ) {
                            $term = get_term( $term_id );
                            if ( $term && ! is_wp_error( $term ) ) {
                                $term_names[] = $term->name;
                            }
                        }
                        $options = $term_names;
                    }

                    $specs[ $name ] = implode( ', ', $options );
                }
            }
        }

        // Add dimensions.
        if ( $product->has_dimensions() ) {
            $specs['מידות'] = $product->get_dimensions();
        }

        // Add weight.
        if ( $product->has_weight() ) {
            $specs['משקל'] = $product->get_weight() . ' ' . get_option( 'woocommerce_weight_unit' );
        }

        // Add SKU.
        $sku = $product->get_sku();
        if ( $sku ) {
            $specs['מק"ט'] = $sku;
        }

        return $specs;
    }

    /**
     * Clean table cell content.
     *
     * @param string $cell Cell content.
     * @return string Clean content.
     */
    private function clean_cell( string $cell ): string {
        $cell = wp_strip_all_tags( $cell );
        $cell = html_entity_decode( $cell, ENT_QUOTES, 'UTF-8' );
        $cell = preg_replace( '/\s+/', ' ', $cell );
        return trim( $cell );
    }

    /**
     * Format specs for display.
     *
     * @param array $specs Specs array.
     * @return string Formatted specs.
     */
    public function format_for_display( array $specs ): string {
        if ( empty( $specs ) ) {
            return '';
        }

        $lines = array( '## מפרט טכני:' );
        foreach ( $specs as $key => $value ) {
            $lines[] = "• {$key}: {$value}";
        }

        return implode( "\n", $lines );
    }
}







