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

namespace SAAI\REST;

use SAAI\Abstracts\Abstract_AI_Agent_REST;
use SAAI\AI_Agents\Vendors\Vendors_Product_Moderator_AI as VendorsProductModeratorAIAgent;
use SAAI\Traits\Singleton_Trait;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

/**
 * Vendors_Product_Moderator_AI REST class.
 *
 * @since 1.0.0
 */
class Vendors_Product_Moderator_AI extends Abstract_AI_Agent_REST {

    use Singleton_Trait;

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

    /**
     * Works as constructor for this class.
     *
     * @since 1.0.0
     * @return void
     */
    public function register_plugin_routes() {
        $this->rest_base = 'wc-vendors-product-moderator-ai';
        parent::register_plugin_routes();
    }

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

        // 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' ),
            )
        );

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/moderate",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'moderate_product' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
                'args'                => array(
                    'product_id' => array(
                        'required'          => true,
                        'type'              => 'integer',
                        'sanitize_callback' => 'absint',
                        'validate_callback' => 'rest_validate_request_arg',
                    ),
                ),
            )
        );
    }

    /**
     * Get the Vendors Product Moderator AI settings.
     *
     * @param \WP_REST_Request $request Request object.
     *
     * @since 1.0.0
     * @since 1.1.4 Added vendors_policy_page_title to response.
     * @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() );

        // Ensure enabled has a default value.
        if ( ! isset( $settings['enabled'] ) ) {
            $settings['enabled'] = 'no';
        }

        // Ensure enable_image_review has a default value.
        if ( ! isset( $settings['enable_image_review'] ) ) {
            $settings['enable_image_review'] = 'no';
        }

        // Ensure vendors_policy_page_id has a default value.
        if ( ! isset( $settings['vendors_policy_page_id'] ) ) {
            $settings['vendors_policy_page_id'] = '';
        }

        // Resolve page title for vendors policy page.
        $settings['vendors_policy_page_title'] = '';
        if ( ! empty( $settings['vendors_policy_page_id'] ) ) {
            $page_title                            = get_the_title( absint( $settings['vendors_policy_page_id'] ) );
            $settings['vendors_policy_page_title'] = $page_title ? $page_title : '';
        }

        return rest_ensure_response( $settings );
    }

    /**
     * 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 enable_image_review setting.
        if ( isset( $params['enable_image_review'] ) ) {
            $sanitized['enable_image_review'] = sanitize_text_field( $params['enable_image_review'] );
        }

        // Sanitize vendors_policy_page_id setting.
        if ( isset( $params['vendors_policy_page_id'] ) ) {
            $page_id = absint( $params['vendors_policy_page_id'] );
            // Only save if it's a valid page ID or empty string.
            if ( $page_id > 0 ) {
                // Verify the page exists.
                $page = get_post( $page_id );
                if ( $page && 'page' === $page->post_type ) {
                    $sanitized['vendors_policy_page_id'] = (string) $page_id;
                } else {
                    $sanitized['vendors_policy_page_id'] = '';
                }
            } else {
                $sanitized['vendors_policy_page_id'] = '';
            }
        }

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

    /**
     * Moderate product via the REST API.
     *
     * @param WP_REST_Request $request The request object.
     *
     * @since 1.0.0
     * @return WP_REST_Response|WP_Error
     */
    public function moderate_product( $request ) {
        $product_id = $request->get_param( 'product_id' );
        $product    = wc_get_product( $product_id );

        if ( ! $product instanceof \WC_Product ) {
            return new WP_Error(
                'invalid_product',
                __( 'Invalid product ID.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 400 )
            );
        }

        // Check if WC Vendors is active.
        $agent = VendorsProductModeratorAIAgent::instance();
        if ( ! $agent->is_wc_vendors_active() ) {
            return new WP_Error(
                'wc_vendors_not_active',
                __( 'WC Vendors plugin is not active.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 400 )
            );
        }

        $result = $agent->run_agent_query(
            array(
                'product_id' => $product_id,
            )
        );

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

        return rest_ensure_response(
            array(
                'success' => true,
                'result'  => $result,
            )
        );
    }
}
