<?php
if (!defined('ABSPATH')) { exit; }

/**
 * PT Smart Detection Engine (PSDE)
 *
 * WooCommerce ürün verilerinin farklı eklenti, taksonomi, özellik ve
 * özel alanlardan güvenli ve tutarlı biçimde algılanmasını sağlar.
 */
class PTMS_Data_Detector {

    /**
     * Ürün markasını ve kaynağını algılar.
     *
     * @param WC_Product|int $product Ürün nesnesi veya ürün kimliği.
     * @return array{value:string,source:string,source_type:string,source_key:string}
     */
    public static function detect_brand($product) {
        if (is_numeric($product)) {
            $product = function_exists('wc_get_product') ? wc_get_product((int) $product) : null;
        }

        if (!$product || !is_a($product, 'WC_Product')) {
            return self::empty_result();
        }

        $product_id = (int) $product->get_id();

        // Öncelik 1: Bilinen marka taksonomileri.
        $taxonomies = array(
            'product_brand'       => 'WooCommerce Brands',
            'pwb-brand'           => 'Perfect Brands for WooCommerce',
            'yith_product_brand'  => 'YITH WooCommerce Brands',
            'berocket_brand'      => 'Brands for WooCommerce',
            'pa_brand'            => __('WooCommerce product feature', 'pw-merchant-api-system'),
            'pa_marka'            => __('WooCommerce product feature', 'pw-merchant-api-system'),
        );

        foreach ($taxonomies as $taxonomy => $source) {
            if (!taxonomy_exists($taxonomy)) { continue; }
            $terms = get_the_terms($product_id, $taxonomy);
            if (is_wp_error($terms) || empty($terms)) { continue; }

            $names = array();
            foreach ($terms as $term) {
                $name = isset($term->name) ? trim(wp_strip_all_tags((string) $term->name)) : '';
                if ($name !== '') { $names[] = $name; }
            }

            $names = array_values(array_unique($names));
            if (!empty($names)) {
                return array(
                    'value'       => implode(', ', $names),
                    'source'      => $source,
                    'source_type' => 'taxonomy',
                    'source_key'  => $taxonomy,
                );
            }
        }

        // Öncelik 2: WooCommerce ürün özellikleri.
        $attributes = array(
            'pa_brand'        => __('Product feature: Brand', 'pw-merchant-api-system'),
            'pa_marka'        => __('Product feature: Brand', 'pw-merchant-api-system'),
            'brand'           => __('Product feature: Brand', 'pw-merchant-api-system'),
            'marka'           => __('Product feature: Brand', 'pw-merchant-api-system'),
            'pa_manufacturer' => __('Product feature: Manufacturer', 'pw-merchant-api-system'),
            'pa_uretici'      => __('Product feature: Manufacturer', 'pw-merchant-api-system'),
            'manufacturer'    => __('Product feature: Manufacturer', 'pw-merchant-api-system'),
            'uretici'         => __('Product feature: Manufacturer', 'pw-merchant-api-system'),
        );

        foreach ($attributes as $attribute => $source) {
            $value = trim(wp_strip_all_tags((string) $product->get_attribute($attribute)));
            if ($value !== '') {
                return array(
                    'value'       => $value,
                    'source'      => $source,
                    'source_type' => 'attribute',
                    'source_key'  => $attribute,
                );
            }
        }

        // Öncelik 3: Sık kullanılan özel alanlar.
        $meta_keys = array(
            '_brand'             => __('Custom field: _brand', 'pw-merchant-api-system'),
            'brand'              => __('Custom field: brand', 'pw-merchant-api-system'),
            '_product_brand'     => __('Custom field: _product_brand', 'pw-merchant-api-system'),
            'product_brand'      => __('Custom field: product_brand', 'pw-merchant-api-system'),
            '_marka'             => __('Custom field: _brand', 'pw-merchant-api-system'),
            'marka'              => __('Special area: brand', 'pw-merchant-api-system'),
            '_manufacturer'      => __('Custom field: _manufacturer', 'pw-merchant-api-system'),
            'manufacturer'       => __('Custom field: manufacturer', 'pw-merchant-api-system'),
            '_wc_product_brand'  => __('Custom field: _wc_product_brand', 'pw-merchant-api-system'),
        );

        foreach ($meta_keys as $meta_key => $source) {
            $raw = get_post_meta($product_id, $meta_key, true);
            $value = self::normalize_value($raw);
            if ($value !== '') {
                return array(
                    'value'       => $value,
                    'source'      => $source,
                    'source_type' => 'meta',
                    'source_key'  => $meta_key,
                );
            }
        }

        return self::empty_result();
    }


    public static function detect_gtin($product) {
        return self::detect_identifier($product, array('_ptms_gtin','_global_unique_id','_wpm_gtin_code','_gtin','gtin','ean','_ean','barcode','_barcode'), array('pa_gtin','pa_ean','gtin','ean','barcode'), 'GTIN/EAN');
    }

    public static function detect_mpn($product) {
        // SKU mağazanın stok kimliğidir; yalnız üretici tarafından atanmış gerçek
        // bir parça numarası açıkça bulunduğunda MPN gönderilir.
        return self::detect_identifier($product, array('_ptms_mpn','_mpn','mpn','_manufacturer_part_number','manufacturer_part_number'), array('pa_mpn','mpn','pa_uretici_kodu','uretici_kodu'), 'MPN');
    }

    private static function detect_identifier($product, array $meta_keys, array $attributes, $label) {
        if (is_numeric($product)) $product=function_exists('wc_get_product')?wc_get_product((int)$product):null;
        if(!$product || !is_a($product,'WC_Product')) return self::empty_result();
        foreach($meta_keys as $key){ $v=self::normalize_value(get_post_meta($product->get_id(),$key,true)); if($v!=='') return array('value'=>$v,'source'=>__('Custom area:', 'pw-merchant-api-system').$key,'source_type'=>'meta','source_key'=>$key); }
        foreach($attributes as $key){ $v=trim(wp_strip_all_tags((string)$product->get_attribute($key))); if($v!=='') return array('value'=>$v,'source'=>__('Product feature:', 'pw-merchant-api-system').$label,'source_type'=>'attribute','source_key'=>$key); }
        return self::empty_result();
    }

    private static function normalize_value($raw) {
        if (is_array($raw)) {
            $values = array();
            foreach ($raw as $item) {
                if (is_scalar($item)) {
                    $item = trim(wp_strip_all_tags((string) $item));
                    if ($item !== '') { $values[] = $item; }
                }
            }
            return implode(', ', array_values(array_unique($values)));
        }

        if (is_scalar($raw)) {
            return trim(wp_strip_all_tags((string) $raw));
        }

        return '';
    }

    private static function empty_result() {
        return array(
            'value'       => '',
            'source'      => '',
            'source_type' => '',
            'source_key'  => '',
        );
    }
}
