<?php
/**
 * Custom Fields API endpoints
 *
 * @package AIPT\Api
 */

namespace AIPT\Api;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

/**
 * Custom Fields API Class
 */
class CustomFields {

    /**
     * Register routes
     */
    public function register_routes() {
        register_rest_route(
            'aipt/v1',
            '/custom-fields',
            array(
                array(
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => array( $this, 'get_custom_fields' ),
                    'permission_callback' => array( $this, 'check_permissions' ),
                    'args'                => array(
                        'per_page' => array(
                            'type'              => 'integer',
                            'default'           => 100,
                            'minimum'           => 1,
                            'maximum'           => 200,
                            'sanitize_callback' => 'absint',
                        ),
                        'page'     => array(
                            'type'              => 'integer',
                            'default'           => 1,
                            'minimum'           => 1,
                            'sanitize_callback' => 'absint',
                        ),
                    ),
                ),
            )
        );

        register_rest_route(
            'aipt/v1',
            '/custom-variables',
            array(
                array(
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => array( $this, 'get_custom_variables' ),
                    'permission_callback' => array( $this, 'check_permissions' ),
                    'args'                => array(
                        'per_page' => array(
                            'type'              => 'integer',
                            'default'           => 100,
                            'minimum'           => 1,
                            'maximum'           => 200,
                            'sanitize_callback' => 'absint',
                        ),
                        'page'     => array(
                            'type'              => 'integer',
                            'default'           => 1,
                            'minimum'           => 1,
                            'sanitize_callback' => 'absint',
                        ),
                    ),
                ),
                array(
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => array( $this, 'save_custom_variable' ),
                    'permission_callback' => array( $this, 'check_permissions' ),
                ),
                array(
                    'methods'             => WP_REST_Server::DELETABLE,
                    'callback'            => array( $this, 'delete_custom_variable' ),
                    'permission_callback' => array( $this, 'check_permissions' ),
                ),
            )
        );
    }

    /**
     * Check if user has permission
     *
     * @return bool
     */
    public function check_permissions() {
        return current_user_can('edit_posts') || current_user_can('manage_woocommerce') || current_user_can('manage_options');
    }

    /**
     * Get saved custom variables
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function get_custom_variables($request) {
        try {
            $variables = get_option('aipt_custom_variables', array());
            

            $unique_variables = array();
            $seen_ids = array();
            
            foreach ($variables as $variable) {
                if (isset($variable['id']) && !in_array($variable['id'], $seen_ids)) {
                    $unique_variables[] = $variable;
                    $seen_ids[] = $variable['id'];
                }
            }
            

            if (count($unique_variables) !== count($variables)) {
                update_option('aipt_custom_variables', $unique_variables);
                $variables = $unique_variables;
            }
            

            $per_page = $request->get_param('per_page');
            $page = $request->get_param('page');
            

            $total = count($variables);
            $offset = ($page - 1) * $per_page;
            $paginated_variables = array_slice($variables, $offset, $per_page);
            

            $response = new WP_REST_Response($paginated_variables, 200);
            $response->header('X-WP-Total', $total);
            $response->header('X-WP-TotalPages', (int) ceil($total / $per_page));
            
            return $response;
        } catch (\Exception $e) {
            return new WP_Error(
                'aipt_custom_variables_error',
                __('Error fetching custom variables.', 'ai-product-tools'),
                array('status' => 500)
            );
        }
    }

    /**
     * Save a custom variable
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function save_custom_variable($request) {
        try {
            $variable = $request->get_json_params();
            
            if (!isset($variable['id']) || !isset($variable['name']) || !isset($variable['field']) || !isset($variable['value'])) {
                return new WP_Error(
                    'invalid_variable',
                    __('Invalid variable data.', 'ai-product-tools'),
                    array('status' => 400)
                );
            }

            $variables = get_option('aipt_custom_variables', array());
            

            $existing_index = -1;
            foreach ($variables as $index => $existing_variable) {
                if (isset($existing_variable['id']) && $existing_variable['id'] === $variable['id']) {
                    $existing_index = $index;
                    break;
                }
            }
            
            if ($existing_index !== -1) {

                $variables[$existing_index] = $variable;
            } else {

                $variables[] = $variable;
            }
            
            update_option('aipt_custom_variables', $variables);

            return new WP_REST_Response($variable, 201);
        } catch (\Exception $e) {
            return new WP_Error(
                'aipt_save_variable_error',
                __('Error saving custom variable.', 'ai-product-tools'),
                array('status' => 500)
            );
        }
    }

    /**
     * Delete a custom variable
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function delete_custom_variable($request) {
        try {
            $variable_id = $request->get_param('id');
            
            if (!$variable_id) {
                return new WP_Error(
                    'invalid_id',
                    __('Invalid variable ID.', 'ai-product-tools'),
                    array('status' => 400)
                );
            }

            $variables = get_option('aipt_custom_variables', array());
            $variables = array_filter($variables, function($var) use ($variable_id) {
                return $var['id'] !== $variable_id;
            });
            
            update_option('aipt_custom_variables', array_values($variables));

            return new WP_REST_Response(true, 200);
        } catch (\Exception $e) {
            return new WP_Error(
                'aipt_delete_variable_error',
                __('Error deleting custom variable.', 'ai-product-tools'),
                array('status' => 500)
            );
        }
    }

    /**
     * Get default WooCommerce product fields
     *
     * @return array
     */
    private function get_default_product_fields() {
        return array(
            array('key' => 'name', 'label' => __('Product Name', 'ai-product-tools')),
            array('key' => 'description', 'label' => __('Description', 'ai-product-tools')),
            array('key' => 'short_description', 'label' => __('Short Description', 'ai-product-tools')),
            array('key' => 'sku', 'label' => __('SKU', 'ai-product-tools')),
            array('key' => 'price', 'label' => __('Price', 'ai-product-tools')),
            array('key' => 'regular_price', 'label' => __('Regular Price', 'ai-product-tools')),
            array('key' => 'sale_price', 'label' => __('Sale Price', 'ai-product-tools')),
            array('key' => 'stock_status', 'label' => __('Stock Status', 'ai-product-tools')),
            array('key' => 'stock_quantity', 'label' => __('Stock Quantity', 'ai-product-tools')),
            array('key' => 'weight', 'label' => __('Weight', 'ai-product-tools')),
            array('key' => 'length', 'label' => __('Length', 'ai-product-tools')),
            array('key' => 'width', 'label' => __('Width', 'ai-product-tools')),
            array('key' => 'height', 'label' => __('Height', 'ai-product-tools')),
        );
    }

    /**
     * Get WooCommerce product attributes
     *
     * @return array
     */
    private function get_product_attributes() {
        try {
            $fields = array();

            if (function_exists('wc_get_attribute_taxonomies')) {
                $attributes = wc_get_attribute_taxonomies();
                foreach ($attributes as $attr) {
                    $key = 'pa_' . $attr->attribute_name;
                    $label = !empty($attr->attribute_label) ? $attr->attribute_label : wc_attribute_label($key);
                    $fields[$key] = $label;
                }
            }

            if (function_exists('wc_get_products')) {
                $products = wc_get_products(array(
                    'limit'  => 50, 
                    'return' => 'objects',
                    'status' => array('publish', 'private', 'draft')
                ));

                foreach ($products as $product) {
                    $product_attributes = $product->get_attributes();
                    if (empty($product_attributes)) {
                        continue;
                    }
                    foreach ($product_attributes as $attribute) {
                        $attr_name = $attribute->get_name(); 

                        $label = function_exists('wc_attribute_label') ? wc_attribute_label($attr_name) : ucfirst(str_replace('_', ' ', $attr_name));
                        if (!isset($fields[$attr_name])) {
                            $fields[$attr_name] = $label;
                        }
                    }
                }
            }

            $result = array();
            foreach ($fields as $key => $label) {
                $result[] = array(
                    'key'   => $key,
                    'label' => $label,
                );
            }

            return $result;
        } catch (\Exception $e) {
            return array();
        }
    }

    /**
     * Get ACF fields if available
     *
     * @return array
     */
    private function get_acf_fields() {
        if (!function_exists('acf_get_field_groups')) {
            return array();
        }

        $acf_fields = array();
        $field_groups = acf_get_field_groups(array('post_type' => 'product'));

        foreach ($field_groups as $group) {
            $fields = acf_get_fields($group);
            foreach ($fields as $field) {
                $acf_fields[] = array(
                    'key' => $field['name'],
                    'label' => $field['label']
                );
            }
        }

        return $acf_fields;
    }

    /**
     * Get custom meta fields
     *
     * @return array
     */
    private function get_custom_meta_fields() {
        global $wpdb;

        try {
            $query = $wpdb->prepare(
                "SELECT DISTINCT pm.meta_key
                FROM {$wpdb->postmeta} pm
                INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                WHERE p.post_type = %s
                AND pm.meta_key NOT LIKE %s
                AND pm.meta_key NOT IN ('_edit_lock', '_edit_last', '_thumbnail_id')
                ORDER BY pm.meta_key ASC",
                'product',
                $wpdb->esc_like('_') . '%'
            );

            $results = $wpdb->get_results($query);

            if ($wpdb->last_error) {
                return array();
            }

            $fields = array_map(function($field) {
                return array(
                    'key' => $field->meta_key,
                    'label' => ucwords(str_replace('_', ' ', $field->meta_key))
                );
            }, $results);
            return $fields;

        } catch (\Exception $e) {
            return array();
        }
    }

    /**
     * Get all custom fields
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error
     */
    public function get_custom_fields($request) {
        try {
            $fields = array(
                'default' => array(
                    'label' => __('Default Fields', 'ai-product-tools'),
                    'fields' => $this->get_default_product_fields()
                ),
                'attributes' => array(
                    'label' => __('Product Attributes', 'ai-product-tools'),
                    'fields' => $this->get_product_attributes()
                ),
                'taxonomies' => array(
                    'label' => __('Taxonomies', 'ai-product-tools'),
                    'fields' => array(
                        array('key' => 'product_cat', 'label' => __('Product Categories', 'ai-product-tools')),
                        array('key' => 'product_tag', 'label' => __('Product Tags', 'ai-product-tools'))
                    )
                ),
                'custom_meta' => array(
                    'label' => __('Custom Fields', 'ai-product-tools'),
                    'fields' => $this->get_custom_meta_fields()
                )
            );

            $acf_fields = $this->get_acf_fields();
            if (!empty($acf_fields)) {
                $fields['acf'] = array(
                    'label' => __('Advanced Custom Fields', 'ai-product-tools'),
                    'fields' => $acf_fields
                );
            }

            foreach ($fields as $group_key => $group) {
                if (!isset($group['label']) || !isset($group['fields']) || !is_array($group['fields'])) {

                    unset($fields[$group_key]);
                }
            }

            return new WP_REST_Response($fields, 200);

        } catch (\Exception $e) {
            return new WP_Error(
                'aipt_custom_fields_error',
                __('Error fetching custom fields.', 'ai-product-tools'),
                array('status' => 500)
            );
        }
    }
} 