<?php
/**
 * Attributes REST API Controller
 *
 * @package VariationHub
 * 
 * phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
 * Reason: Queries wp_term_taxonomy/wp_terms for attribute metadata. WordPress wp_cache_* handles term caching,
 * but direct queries needed for complex attribute relationships. Performance-critical attribute operations.
 */

namespace VariationHub\API;

use VariationHub\Core\License_Manager;

defined('ABSPATH') || exit;

/**
 * Attributes Controller Class
 */
class Attributes_Controller extends \WP_REST_Controller {
    
    /**
     * Namespace
     *
     * @var string
     */
    protected $namespace = 'variation-hub/v1';
    
    /**
     * Rest base
     *
     * @var string
     */
    protected $rest_base = 'attributes';
    
    /**
     * Register routes
     */
    public function register_routes() {
        // GET /attributes - List all attributes
        register_rest_route($this->namespace, '/' . $this->rest_base, [
            [
                'methods'             => \WP_REST_Server::READABLE,
                'callback'            => [$this, 'get_attributes'],
                'permission_callback' => [$this, 'get_items_permissions_check'],
            ],
        ]);
        
        // POST /attributes/convert - Convert local to global attribute
        register_rest_route($this->namespace, '/' . $this->rest_base . '/convert', [
            [
                'methods'             => \WP_REST_Server::CREATABLE,
                'callback'            => [$this, 'convert_to_global'],
                'permission_callback' => [$this, 'update_items_permissions_check'],
                'args'                => $this->get_convert_args(),
            ],
        ]);
    }
    
    /**
     * Get all attributes (global + local)
     *
     * @param \WP_REST_Request $request Full request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function get_attributes($request) {
        global $wpdb;
        
        $attributes = [];
        
        // 1. Global attributes (taxonomy-based)
        $global_attrs = wc_get_attribute_taxonomies();
        
        foreach ($global_attrs as $attr) {
            $taxonomy = wc_attribute_taxonomy_name($attr->attribute_name);
            $terms = get_terms([
                'taxonomy' => $taxonomy,
                'hide_empty' => false,
            ]);
            
            // Count variations using this attribute
            $usage_count = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(DISTINCT pm.post_id) 
                 FROM {$wpdb->postmeta} pm
                 INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                 WHERE p.post_type = 'product_variation'
                 AND pm.meta_key = %s",
                'attribute_' . $taxonomy
            ));
            
            $attributes[] = [
                'id' => $attr->attribute_id,
                'name' => $taxonomy,
                'label' => $attr->attribute_label,
                'slug' => $attr->attribute_name,
                'type' => $attr->attribute_type ?: 'select',
                'is_global' => true,
                'terms' => array_map(function($term) {
                    return [
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'slug' => $term->slug,
                        'count' => $term->count,
                    ];
                }, $terms),
                'used_in_variations' => (int) $usage_count,
            ];
        }
        
        // 2. Local attributes (product-specific)
        // ✅ BUGFIX: Cross-reference with registered taxonomies to avoid false positives
        $registered_taxonomies = array_map(
            function($attr) {
                return 'attribute_' . wc_attribute_taxonomy_name($attr->attribute_name);
            },
            $global_attrs
        );
        
        $local_attrs_query = $wpdb->get_results(
            "SELECT DISTINCT meta_key 
             FROM {$wpdb->postmeta} pm
             INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
             WHERE p.post_type = 'product_variation'
             AND meta_key LIKE 'attribute_%'
             AND meta_key NOT LIKE 'attribute_pa_%'
             ORDER BY meta_key"
        );
        
        foreach ($local_attrs_query as $row) {
            // ✅ BUGFIX: Skip if this attribute is actually a registered global taxonomy
            if (in_array($row->meta_key, $registered_taxonomies, true)) {
                continue;
            }
            
            $attr_name = str_replace('attribute_', '', $row->meta_key);
            
            // Get unique values
            $values = $wpdb->get_col($wpdb->prepare(
                "SELECT DISTINCT meta_value 
                 FROM {$wpdb->postmeta} pm
                 INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                 WHERE p.post_type = 'product_variation'
                 AND meta_key = %s
                 AND meta_value != ''
                 ORDER BY meta_value",
                $row->meta_key
            ));
            
            // Count usage
            $usage_count = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(DISTINCT post_id) 
                 FROM {$wpdb->postmeta} pm
                 INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                 WHERE p.post_type = 'product_variation'
                 AND meta_key = %s",
                $row->meta_key
            ));
            
            $attributes[] = [
                'id' => 0,
                'name' => $attr_name,
                'label' => ucfirst(str_replace(['-', '_'], ' ', $attr_name)),
                'slug' => $attr_name,
                'type' => 'select',
                'is_global' => false,
                'terms' => array_map(function($value, $index) {
                    return [
                        'id' => 0,
                        'name' => $value,
                        'slug' => sanitize_title($value),
                        'count' => 0,
                    ];
                }, $values, array_keys($values)),
                'used_in_variations' => (int) $usage_count,
                'values' => $values,
            ];
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => [
                'attributes' => $attributes,
                'total' => count($attributes),
                'global_count' => count($global_attrs),
                'local_count' => count($local_attrs_query),
            ],
        ]);
    }
    
    /**
     * Convert local attribute to global
     *
     * @param \WP_REST_Request $request Full request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function convert_to_global($request) {
        // 🔒 SECURITY: Attribute Manager is a PRO-only feature
        if (!License_Manager::has_feature('attribute_manager')) {
            return new \WP_Error(
                'variation_hub_attribute_manager_pro_only',
                __('Attribute Manager is available in PRO version only. Please upgrade to access this feature.', 'variation-hub'),
                ['status' => 403]
            );
        }

        global $wpdb;

        $params = $request->get_params(); // Changed from get_json_params()
        $local_attr_name = isset($params['local_attribute']) ? sanitize_text_field($params['local_attribute']) : '';
        $new_global_name = isset($params['new_global_name']) ? sanitize_text_field($params['new_global_name']) : '';

        if (empty($local_attr_name) || empty($new_global_name)) {
            return new \WP_Error(
                'variation_hub_missing_params',
                __('Missing parameters', 'variation-hub'),
                ['status' => 400]
            );
        }
        
        // Remove pa_ prefix if user included it (wc_create_attribute adds it automatically)
        $attribute_slug = preg_replace('/^pa_/', '', $new_global_name);
        
        // Create global attribute if doesn't exist
        $attribute_id = wc_create_attribute([
            'name' => ucfirst(str_replace(['-', '_'], ' ', $attribute_slug)),
            'slug' => $attribute_slug,
            'type' => 'select',
            'order_by' => 'menu_order',
            'has_archives' => false,
        ]);
        
        if (is_wp_error($attribute_id)) {
            return $attribute_id;
        }
        
        $taxonomy = wc_attribute_taxonomy_name($attribute_slug);
        
        // Register taxonomy
        register_taxonomy($taxonomy, ['product'], []);
        
        // Get all local attribute values
        $local_values = $wpdb->get_results($wpdb->prepare(
            "SELECT DISTINCT pm.post_id, pm.meta_value
             FROM {$wpdb->postmeta} pm
             INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
             WHERE p.post_type = 'product_variation'
             AND pm.meta_key = %s
             AND pm.meta_value != ''",
            'attribute_' . $local_attr_name
        ));
        
        $converted_count = 0;
        $created_terms = [];
        
        foreach ($local_values as $row) {
            $value = $row->meta_value;
            $variation_id = $row->post_id;
            
            // Create term if doesn't exist
            $term = term_exists($value, $taxonomy);
            if (!$term) {
                $term = wp_insert_term($value, $taxonomy);
                if (!is_wp_error($term)) {
                    $created_terms[] = $value;
                }
            }
            
            if (!is_wp_error($term)) {
                $term_slug = is_array($term) ? get_term($term['term_id'], $taxonomy)->slug : get_term($term, $taxonomy)->slug;
                
                // Update variation meta
                update_post_meta($variation_id, 'attribute_' . $taxonomy, $term_slug);
                
                // Delete old local attribute
                delete_post_meta($variation_id, 'attribute_' . $local_attr_name);
                
                $converted_count++;
            }
        }
        
        return rest_ensure_response([
            'success' => true,
            'message' => sprintf(
                /* translators: %d: number of variations with converted attributes */
                __('%d variation attributes converted successfully', 'variation-hub'),
                $converted_count
            ),
            'data' => [
                'processed_variations' => $converted_count,
                'created_terms' => array_unique($created_terms),
                'new_taxonomy' => $taxonomy,
            ],
        ]);
    }
    
    /**
     * Check if user can view items
     *
     * @param \WP_REST_Request $request Full request object.
     * @return bool
     */
    public function get_items_permissions_check($request) {
        return current_user_can('manage_woocommerce');
    }
    
    /**
     * Check if user can update items
     *
     * @param \WP_REST_Request $request Full request object.
     * @return bool
     */
    public function update_items_permissions_check($request) {
        return current_user_can('manage_woocommerce');
    }
    
    /**
     * Get convert args
     *
     * @return array
     */
    protected function get_convert_args() {
        return [
            'local_attribute' => [
                'description' => __('Local attribute name', 'variation-hub'),
                'type'        => 'string',
                'required'    => true,
                'sanitize_callback' => 'sanitize_text_field',
            ],
            'new_global_name' => [
                'description' => __('New global attribute name', 'variation-hub'),
                'type'        => 'string',
                'required'    => true,
                'sanitize_callback' => 'sanitize_text_field',
            ],
        ];
    }
}
