<?php

if (!defined('ABSPATH')) {
    exit;
}

class AIEO_DMM_Problematic_Variations extends AIEO_DMM_Module_Base {

    public function get_id()       { return 'problematic_variations'; }
    public function get_label()    { return __('Multi-Attribute Variations', 'ai-eshop-optimizer'); }
    public function get_group()    { return 'catalog_sync'; }
    public function get_priority() { return 73; } 

    
    const OPTION_BLOCK = 'aieo_dmm_block_multi_attr_variations';

    
    public static function block_enabled() {
        return get_option(self::OPTION_BLOCK, '0') === '1';
    }

    public function register_hooks() {
        add_action('admin_enqueue_scripts', array($this, 'maybe_enqueue_guard'));
        add_action('woocommerce_admin_process_product_object', array($this, 'warn_on_save'), 99, 1);
        add_action('wp_ajax_aieo_dmm_mav_save', array($this, 'ajax_save_settings'));
    }

    
    public function ajax_save_settings() {
        AIEO_DMM::verify_ajax_request();
        $block = !empty($_POST['block']) ? '1' : '0'; 
        update_option(self::OPTION_BLOCK, $block, false);
        wp_send_json_success(array(
            'block'   => $block,
            'message' => ($block === '1')
                ? __('Protection ON — products that use more than one attribute for variations are blocked on save.', 'ai-eshop-optimizer')
                : __('Protection OFF — products may use multiple variation attributes (e.g. colour × size). The list below is informational only.', 'ai-eshop-optimizer'),
        ));
    }

    
    public function maybe_enqueue_guard($hook) {
        if (!self::block_enabled()) { return; } 
        if (!in_array($hook, array('post.php', 'post-new.php'), true)) { return; }
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || $screen->post_type !== 'product') { return; }
        if (!defined('AIEO_FILE')) { return; }
        $rel  = 'assets/js/dmm-variation-attr-guard.js';
        $path = dirname(AIEO_FILE) . '/' . $rel;
        if (!is_readable($path)) { return; }
        wp_enqueue_script('aieo-dmm-variation-attr-guard', plugins_url($rel, AIEO_FILE), array('jquery'), (string) filemtime($path), true);
        wp_localize_script('aieo-dmm-variation-attr-guard', 'AIEO_VAR_GUARD', array(
            'msg' => __('This product has more than one attribute set as “Used for variations”. Only one is allowed — untick the extras in the Attributes tab, then save.', 'ai-eshop-optimizer'),
        ));
    }

    
    public function warn_on_save($product) {
        if (!self::block_enabled()) { return; } 
        if (!is_object($product) || !method_exists($product, 'is_type') || !$product->is_type('variable')) { return; }
        if (self::count_variation_attrs($product) > 1 && class_exists('WC_Admin_Meta_Boxes') && method_exists('WC_Admin_Meta_Boxes', 'add_error')) {
            WC_Admin_Meta_Boxes::add_error(__('Heads up: this product uses more than one attribute for variations. If that is intentional (e.g. colour × size), turn off the guard under Catalog Sync → Multi-Attribute Variations; otherwise untick the extras so one remains.', 'ai-eshop-optimizer'));
        }
    }

    
    private static function count_variation_attrs($product) {
        $n = 0;
        foreach ($product->get_attributes() as $a) {
            if (is_object($a) && method_exists($a, 'get_variation') && $a->get_variation()) { $n++; }
        }
        return $n;
    }

    
    public static function get_problematic($limit = 1000) {
        global $wpdb;
        $rows = $wpdb->get_results(
            "SELECT pm.post_id, pm.meta_value
               FROM {$wpdb->postmeta} pm
               JOIN {$wpdb->posts} p ON p.ID = pm.post_id AND p.post_type = 'product' AND p.post_status NOT IN ('trash','auto-draft')
               JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
               JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'product_type'
               JOIN {$wpdb->terms} t ON t.term_id = tt.term_id AND t.slug = 'variable'
              WHERE pm.meta_key = '_product_attributes'",
            ARRAY_A
        );
        $flagged = array();
        foreach ((array) $rows as $r) {
            $attrs = maybe_unserialize($r['meta_value']);
            if (!is_array($attrs)) { continue; }
            $names = array();
            foreach ($attrs as $key => $a) {
                if (is_array($a) && !empty($a['is_variation'])) {
                    $nm = (!empty($a['name'])) ? (string) $a['name'] : (string) $key;
                    $names[] = (strpos($nm, 'pa_') === 0 && function_exists('wc_attribute_label')) ? wc_attribute_label($nm) : $nm;
                }
            }
            if (count($names) > 1) { $flagged[(int) $r['post_id']] = $names; }
        }
        if (empty($flagged)) { return array(); }

        $ids = array_slice(array_map('intval', array_keys($flagged)), 0, max(1, (int) $limit));
        $in  = implode(',', $ids);
        $meta = $wpdb->get_results(
            "SELECT p.ID, p.post_title, sku.meta_value AS sku
               FROM {$wpdb->posts} p
               LEFT JOIN {$wpdb->postmeta} sku ON sku.post_id = p.ID AND sku.meta_key = '_sku'
              WHERE p.ID IN ($in)",
            OBJECT_K
        );
        $out = array();
        foreach ($ids as $pid) {
            $out[] = array(
                'id'    => $pid,
                'name'  => isset($meta[$pid]) ? (string) $meta[$pid]->post_title : ('#' . $pid),
                'sku'   => isset($meta[$pid]) ? (string) $meta[$pid]->sku : '',
                'count' => count($flagged[$pid]),
                'attrs' => $flagged[$pid],
            );
        }
        usort($out, static function ($a, $b) { return $b['count'] <=> $a['count']; });
        return $out;
    }

    public function render_subtab() {
        $this->render_template('problematic-variations.php', array(
            'rows'          => self::get_problematic(1000),
            'block_enabled' => self::block_enabled(),
            'module'        => $this,
        ));
    }
}
