<?php
/**
 * Author: Rymera Web Co.
 *
 * @package SAAI\REST
 */

namespace SAAI\REST;

use SAAI\Abstracts\Abstract_AI_Agent_REST;
use SAAI\AI_Agents\Product_Description_AI as AI_Agent;
use SAAI\Classes\Product_Description;
use SAAI\Traits\Singleton_Trait;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use SAAI\AI_Agents\Sub_Agent\Product_Description_Form_Fill_AI;
/**
 * Product_Questions class.
 *
 * @since 1.0.0
 */
class Product_Description_AI extends Abstract_AI_Agent_REST {

    use Singleton_Trait;

    /**
     * Holds the class instance object
     *
     * @since 1.0.0
     * @var Product_Description_AI $instance object
     */
    protected static $instance;

    /**
     * Sanitize settings data before saving.
     *
     * @param array $params The parameters to sanitize.
     * @return array The sanitized parameters.
     */
    protected function sanitize_settings_data( $params ) {
        $sanitized = array();

        // Sanitize enabled setting.
        if ( isset( $params['enabled'] ) ) {
            $sanitized['enabled'] = sanitize_text_field( $params['enabled'] );
        }

        // Sanitize description_length (text).
        if ( isset( $params['description_length'] ) ) {
            $sanitized['description_length'] = sanitize_text_field( $params['description_length'] );
        }

        // Sanitize refund_guarantee (text).
        if ( isset( $params['refund_guarantee'] ) ) {
            $sanitized['refund_guarantee'] = sanitize_text_field( $params['refund_guarantee'] );
        }

        // Sanitize main description length check settings.
        if ( isset( $params['main_desc_length_check'] ) ) {
            $sanitized['main_desc_length_check'] = sanitize_text_field( $params['main_desc_length_check'] );
        }

        if ( isset( $params['main_desc_check_frequency'] ) ) {
            $sanitized['main_desc_check_frequency'] = absint( $params['main_desc_check_frequency'] );
        }

        if ( isset( $params['main_desc_min_word_count'] ) ) {
            $sanitized['main_desc_min_word_count'] = absint( $params['main_desc_min_word_count'] );
        }

        if ( isset( $params['main_desc_max_word_count'] ) ) {
            $sanitized['main_desc_max_word_count'] = absint( $params['main_desc_max_word_count'] );
        }

        // Sanitize language (text).
        if ( isset( $params['language'] ) ) {
            $sanitized['language'] = sanitize_text_field( $params['language'] );
        }

        // Sanitize array fields.
        $array_fields = array( 'tones', 'interesting_facts', 'age_focus', 'target_audience' );
        foreach ( $array_fields as $field ) {
            if ( isset( $params[ $field ] ) && is_array( $params[ $field ] ) ) {
                $sanitized[ $field ] = array_map( 'sanitize_text_field', $params[ $field ] );
            }
        }

        // Apply filter for additional sanitization.
        return apply_filters( 'saai_sanitize_product_description_settings', $sanitized, $params );
    }

    /**
     * Register the routes.
     *
     * @since 1.0.0
     * @return void
     */
    public function register_routes() {

        parent::register_routes();

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/(?P<product_id>[\d]+)",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'generate_product_description' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/form-fill/(?P<product_id>[\d]+)",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'generate_product_description_form_fill' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );
        // Add endpoint to get settings.
        register_rest_route(
            $this->namespace,
            "/$this->rest_base/settings",
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_settings' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );
    }

    /**
     * Generate product description.
     *
     * @since 1.0.0
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response Response object.
     */
    public function generate_product_description( $request ) {
        $product_id = $request['product_id'] ?? 0;

        if ( ! $product_id || 'product' !== get_post_type( $product_id ) ) {
            return new WP_Error( 'invalid_product_id', 'Invalid product ID', array( 'status' => 400 ) );
        }

        $params              = Product_Description::sanitize_data( $request->get_params() );
        $product_description = new Product_Description( $product_id );
        $product_description->set_data( $params );
        $check = $product_description->save();

        if ( is_wp_error( $check ) ) {
            return $check;
        }

        $ai_response = AI_Agent::instance()->run_agent_query( array( 'product_id' => $product_id ) );

        if ( is_wp_error( $ai_response ) ) {
            return $ai_response;
        }

        $completion = $this->with_usage_data( $ai_response['completion'] );
        $response   = rest_ensure_response( $completion );

        return new WP_REST_Response( $response, 200 );
    }

    /**
     * Generate product description form fill.
     *
     * @since 1.0.4
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response Response object.
     */
    public function generate_product_description_form_fill( $request ) {
        $product_id = absint( $request['product_id'] );
        $product    = wc_get_product( $product_id );

        if ( ! $product instanceof \WC_Product ) {
            return new WP_Error( 'invalid_product', 'Invalid product', array( 'status' => 400 ) );
        }

        $check = AI_Agent::instance()->run_product_description_form_fill( $product );

        if ( is_wp_error( $check ) ) {
            return $check;
        }

        return new WP_REST_Response( true, 200 );
    }

    /**
     * Get the Product Description AI settings.
     *
     * @since 1.0.4
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response Response object.
     */
    public function get_settings( $request ) {
        $ai_agent_key = $this->get_option_key();
        $settings     = get_option( $ai_agent_key, array() );

        $response = array(
            'settings' => $settings,
        );

        return $this->rest_response( $response, $request );
    }
}
