<?php
/**
 * Chat Feedback REST Controller
 *
 * Handles REST API endpoints for chat feedback functionality.
 *
 * @package SAAI\REST\Chat
 */

namespace SAAI\REST\Chat;

use SAAI\Abstracts\Abstract_REST;
use SAAI\Traits\Singleton_Trait;
use SAAI\Classes\Chat\Chat_Feedback;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

defined( 'ABSPATH' ) || exit;

/**
 * Chat_Feedback_Controller REST API controller class.
 *
 * @since 1.0.0
 */
class Chat_Feedback_Controller extends Abstract_REST {

    use Singleton_Trait;

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

    /**
     * REST constructor.
     *
     * @since 1.0.0
     */
    public function __construct() {
    }

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

    /**
     * Register the routes for Chat Feedback.
     *
     * @since 1.0.0
     * @return void
     */
    public function register_routes() {
        // Get feedback settings endpoint.
        register_rest_route(
            $this->namespace,
            '/settings/feedback',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_feedback_settings' ),
                'permission_callback' => array( $this, 'get_settings_permissions_check' ),
            )
        );

        // Update feedback settings endpoint.
        register_rest_route(
            $this->namespace,
            '/settings/feedback',
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'update_feedback_settings' ),
                'permission_callback' => array( $this, 'update_settings_permissions_check' ),
                'args'                => array(
                    'feedback_enabled'                => array(
                        'type'              => 'boolean',
                        'description'       => __( 'Enable customer feedback collection.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'rest_sanitize_boolean',
                    ),
                    'request_reason_on_negative'      => array(
                        'type'              => 'boolean',
                        'description'       => __( 'Request reason on negative feedback.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'rest_sanitize_boolean',
                    ),
                    'escalation_enabled'              => array(
                        'type'              => 'boolean',
                        'description'       => __( 'Enable support escalation.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'rest_sanitize_boolean',
                    ),
                    'escalation_support_url'          => array(
                        'type'              => 'string',
                        'description'       => __( 'Support URL for escalation.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'esc_url_raw',
                    ),
                    'escalation_on_negative_feedback' => array(
                        'type'              => 'boolean',
                        'description'       => __( 'Offer escalation after negative feedback.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'rest_sanitize_boolean',
                    ),
                    'feedback_prompt_text'            => array(
                        'type'              => 'string',
                        'description'       => __( 'Text displayed in the feedback prompt.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                    'skip_button_text'                => array(
                        'type'              => 'string',
                        'description'       => __( 'Text displayed on the skip button.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                    'escalation_email_enabled'        => array(
                        'type'              => 'boolean',
                        'description'       => __( 'Enable email escalation on support request.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'rest_sanitize_boolean',
                    ),
                    'escalation_email_recipient'      => array(
                        'type'              => 'string',
                        'description'       => __( 'Recipient email for escalation emails.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'sanitize_email',
                    ),
                    'escalation_email_intro'          => array(
                        'type'              => 'string',
                        'description'       => __( 'Intro text for escalation emails.', 'storeagent-ai-for-woocommerce' ),
                        'sanitize_callback' => 'sanitize_textarea_field',
                    ),
                ),
            )
        );
    }

    /**
     * Get feedback settings.
     *
     * @param WP_REST_Request $request The request object.
     * @return WP_REST_Response The response object.
     */
    public function get_feedback_settings( $request ) {
        // Get settings filtered by current plan.
        $settings = Chat_Feedback::get_feedback_settings_for_plan();

        /**
         * Filter feedback settings before returning to frontend.
         *
         * @param array $settings Feedback settings.
         */
        $settings = apply_filters( 'storeagent_feedback_settings', $settings );

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

    /**
     * Update feedback settings.
     *
     * @param WP_REST_Request $request The request object.
     * @return WP_REST_Response|WP_Error The response object or error.
     */
    public function update_feedback_settings( $request ) {
        // Extract settings from request.
        $settings = array();
        $params   = array(
            'feedback_enabled',
            'request_reason_on_negative',
            'escalation_enabled',
            'escalation_support_url',
            'escalation_on_negative_feedback',
            'feedback_prompt_text',
            'skip_button_text',
            'escalation_email_enabled',
            'escalation_email_recipient',
            'escalation_email_intro',
        );

        foreach ( $params as $param ) {
            if ( null !== $request->get_param( $param ) ) {
                $settings[ $param ] = $request->get_param( $param );
            }
        }

        // Prevent free users from enabling escalation.
        if ( ! Chat_Feedback::is_escalation_available() ) {
            if ( isset( $settings['escalation_enabled'] ) && $settings['escalation_enabled'] ) {
                return new WP_Error(
                    'escalation_not_available',
                    __( 'Support escalation is only available on paid plans. Please upgrade to access this feature.', 'storeagent-ai-for-woocommerce' ),
                    array( 'status' => 403 )
                );
            }

            // Remove escalation settings from update.
            unset( $settings['escalation_enabled'] );
            unset( $settings['escalation_support_url'] );
            unset( $settings['escalation_on_negative_feedback'] );
            unset( $settings['escalation_email_enabled'] );
            unset( $settings['escalation_email_recipient'] );
            unset( $settings['escalation_email_intro'] );
        }

        // Validate settings.
        $validation = Chat_Feedback::validate_feedback_settings( $settings );
        if ( is_wp_error( $validation ) ) {
            return new WP_Error(
                $validation->get_error_code(),
                $validation->get_error_message(),
                array( 'status' => 400 )
            );
        }

        // Sanitize settings.
        $settings = Chat_Feedback::sanitize_feedback_settings( $settings );

        // Update settings.
        $updated = Chat_Feedback::update_feedback_settings( $settings );

        if ( ! $updated ) {
            return new WP_Error(
                'update_failed',
                __( 'Failed to update feedback settings.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 500 )
            );
        }

        return $this->rest_response(
            array(
                'success'  => true,
                'message'  => __( 'Feedback settings updated successfully.', 'storeagent-ai-for-woocommerce' ),
                'settings' => Chat_Feedback::get_feedback_settings(),
            ),
            $request
        );
    }

    /**
     * Check permissions for getting settings.
     *
     * Allows public access for frontend chat widget functionality.
     * Settings are not sensitive and need to be accessible to all users
     * so the chat widget can display feedback options correctly.
     *
     * @param WP_REST_Request $request The request object.
     * @return bool|WP_Error True if allowed, WP_Error otherwise.
     */
    public function get_settings_permissions_check( $request ) {
        // Allow any user to get settings (needed for frontend).
        return true;
    }

    /**
     * Check permissions for updating settings.
     *
     * @param WP_REST_Request $request The request object.
     * @return bool|WP_Error True if allowed, WP_Error otherwise.
     */
    public function update_settings_permissions_check( $request ) {
        // Only admins can update settings.
        return current_user_can( 'manage_options' );
    }
}
