<?php

namespace AIPT\Api\BulkGenerator\Title;

use AIPT\Core\ErrorHandler;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use AIPT\Api\BulkGenerator\Title\TitleGeneratorService;

class TitleGeneratorController {
    use \AIPT\Api\Traits\RateLimitTrait;

    private $service;

    public function __construct() {
        $this->service = new TitleGeneratorService();
    }

    public function register_routes() {

        register_rest_route('aipt/v1', '/title-generator/bulk-generate', [
            'methods' => 'POST',
            'callback' => [$this, 'bulk_generate'],
            'permission_callback' => [$this, 'check_permissions'],
            'args' => [
                'productIds' => [
                    'type' => 'array',
                    'required' => true,
                    'sanitize_callback' => function ($param) {
                        return array_map('absint', $param);
                    }
                ],
                'options' => [
                    'type' => 'object',
                    'required' => true
                ]
            ]
        ]);

        register_rest_route('aipt/v1', '/title-generator/bulk-apply', [
            'methods' => 'POST',
            'callback' => [$this, 'bulk_apply'],
            'permission_callback' => [$this, 'check_permissions'],
            'args' => [
                'results' => [
                    'type' => 'array',
                    'required' => true
                ],
                'options' => [
                    'type' => 'object',
                    'required' => false
                ]
            ]
        ]);

        register_rest_route('aipt/v1', '/title-generator/bulk-reject', [
            'methods' => 'POST',
            'callback' => [$this, 'bulk_reject'],
            'permission_callback' => [$this, 'check_permissions'],
            'args' => [
                'results' => [
                    'required' => true,
                    'type' => 'array',
                    'items' => [
                        'type' => 'object',
                        'properties' => [
                            'product_id' => [
                                'required' => true,
                                'type' => 'integer'
                            ]
                        ]
                    ]
                ]
            ]
        ]);

    }

    public function check_permissions() {
        return current_user_can('manage_woocommerce');
    }
    
    /**
     * Apply premium feature controls to options.
     *
     * Uses filter hook to allow Premium module to preserve premium options.
     * Free version always uses default values for premium features.
     *
     * @param array $options Request options.
     * @return array Validated options.
     */
    private function applyPremiumControls( $options ) {

        $default_options = array(
            'tone'         => 'SEO-Focused',
            'keywords'     => '',
            'mode'         => 'rewrite',
            'titleSources' => array( 'product_description' ),
        );

        $controlled_options = array_merge( $options, $default_options );

        /**
         * Filter title generator validated options.
         *
         * Premium module can hook here to preserve premium option values
         * when a valid license is present.
         *
         * @since 2.5.0
         * @param array $controlled_options Options with free defaults applied.
         * @param array $options            Original request options.
         */
        $controlled_options = apply_filters( 'aipt_title_validate_options', $controlled_options, $options );

        return $controlled_options;
    }

    public function bulk_generate(WP_REST_Request $request) {
        try {
            $rate_check = $this->checkRateLimit((int) get_current_user_id(), 'title');
            if (!$rate_check['allowed']) { return $this->rateLimitResponse($rate_check); }

            $data = $request->get_json_params();
            $products = $data['productIds'] ?? [];
            $options = $data['options'] ?? [];
            

            $options = $this->applyPremiumControls($options);
            
			if (empty($products)) {
				throw new \Exception( esc_html__( 'No products provided.', 'ai-product-tools' ) );
			}

            if (!is_array($products)) {
                throw new \Exception('Invalid products format. Expected array.');
            }

            $result = $this->service->bulk_generate($products, $options);

            return new WP_REST_Response([
                'results' => $result,
                'success' => true
            ], 200);

        } catch (\Exception $e) {
            $error_message = $e->getMessage();
            $api_provider = $options['provider'] ?? get_option('aipt_api_provider', 'openai');
            $provider_name = ucfirst($api_provider);

            $readable_error = ErrorHandler::make_urls_readable($error_message);

            if (strpos($error_message, 'API Error') !== false) {
                $readable_error = ErrorHandler::format_api_error_message($provider_name, $error_message);
            }

            return ErrorHandler::create_wp_error($readable_error, 'aipt_title_generation_error');
        }
    }

    public function bulk_apply($request) {
        try {
            $params = $request->get_json_params();
            $results = $params['results'] ?? [];

            if (empty($results)) {
                return new \WP_Error('invalid_request', __('No titles to apply', 'ai-product-tools'), ['status' => 400]);
            }

            $success_count = 0;
            $skipped_count = 0;
            $failed_ids = [];
            $total_processed = 0;

            foreach ($results as $result) {
                $product_id = $result['product_id'] ?? null;
                $title = $result['title'] ?? null;
                $status = $result['status'] ?? 'pending';

                if (!$product_id || !$title) {
                    $skipped_count++;
                    continue;
                }

            if ($status === 'rejected') {
                $skipped_count++;
                continue;
            }

            $product = wc_get_product($product_id);
            if (!$product || !is_object($product)) {
                $skipped_count++;
                continue;
            }

            $total_processed++;

                $sanitized_title = sanitize_text_field($title);
                $product->set_name($sanitized_title);
                

                $save_result = $product->save();
                
                if ( is_wp_error( $save_result ) ) {
                    $failed_ids[] = $product_id;
                } elseif ( $save_result && $save_result > 0 ) {
                    $success_count++;
                } else {
                    $failed_ids[] = $product_id;
                }
            }

            $overall_success = $success_count > 0;
            

            if ($success_count === $total_processed && $total_processed > 0) {
                $message = sprintf(
                    /* translators: %d: Number of titles applied */
                    __('%d title(s) applied successfully.', 'ai-product-tools'),
                    $success_count
                );
            } elseif ($success_count > 0) {
                $message = sprintf(
                    /* translators: %1$d: Number of successful updates, %2$d: Number of failed updates */
                    __('%1$d title(s) applied successfully, %2$d failed.', 'ai-product-tools'),
                    $success_count,
                    count($failed_ids)
                );
            } elseif ($total_processed === 0) {
                $message = __('No valid titles to apply. All items were skipped.', 'ai-product-tools');
            } else {
                $message = __('No titles were applied. All updates failed.', 'ai-product-tools');
            }

            return new \WP_REST_Response([
                'success' => $overall_success,
                'message' => $message,
                'data' => [
                    'total_processed' => $total_processed,
                    'updated' => $success_count,
                    'skipped' => $skipped_count,
                    'failed' => count($failed_ids),
                    'failed_ids' => $failed_ids
                ]
            ], 200);

        } catch (\Exception $e) {

            $message = ErrorHandler::sanitize_error_for_display($e->getMessage());
            $status  = ErrorHandler::extract_http_status_from_message($message, 500);
            return new \WP_Error('apply_error', $message, ['status' => $status]);
        }
    }

    public function bulk_reject($request) {
        try {
            $params = $request->get_json_params();
            $results = $params['results'] ?? [];

            if (empty($results)) {
                return new \WP_Error('invalid_request', __('No titles to reject', 'ai-product-tools'), ['status' => 400]);
            }

            $success_count = count($results);

            return new \WP_REST_Response([
                'success' => true,
                'message' => sprintf(
                    /* translators: %d: Number of titles that were rejected */
                    __('%d title(s) rejected successfully.', 'ai-product-tools'),
                    $success_count
                ),
                'rejected_count' => $success_count
            ], 200);

        } catch (\Exception $e) {

            $message = ErrorHandler::sanitize_error_for_display($e->getMessage());
            $status  = ErrorHandler::extract_http_status_from_message($message, 500);
            return new \WP_Error('server_error', $message, ['status' => $status]);
        }
    }
}
