<?php
/**
 * Chat Feedback Class
 *
 * Manages chat feedback settings and configuration.
 *
 * @package SAAI\Classes\Chat
 */

namespace SAAI\Classes\Chat;

use SAAI\Traits\Singleton_Trait;
use WP_Error;

defined( 'ABSPATH' ) || exit;

/**
 * Chat_Feedback Class
 *
 * @since 1.0.0
 */
class Chat_Feedback {

    use Singleton_Trait;

    /**
     * WordPress option key for feedback settings.
     *
     * @since 1.0.0
     */
    const OPTION_KEY_FEEDBACK = 'saai_feedback_settings';

    /**
     * Run the chat feedback class.
     *
     * @since 1.0.0
     */
    public function run() {
        // Hook to initialize settings if needed.
    }

    /**
     * Get feedback settings.
     *
     * @return array Feedback settings.
     */
    public static function get_feedback_settings() {
        $defaults       = self::get_default_feedback_settings();
        $saved_settings = get_option( self::OPTION_KEY_FEEDBACK, array() );

        return wp_parse_args( $saved_settings, $defaults );
    }

    /**
     * Update feedback settings.
     *
     * @param array $settings Settings to update.
     * @return bool Whether the settings were updated successfully.
     */
    public static function update_feedback_settings( $settings ) {
        // Merge with existing settings.
        $current_settings = self::get_feedback_settings();
        $new_settings     = wp_parse_args( $settings, $current_settings );

        return update_option( self::OPTION_KEY_FEEDBACK, $new_settings );
    }

    /**
     * Get default feedback settings.
     *
     * @return array Default feedback settings.
     */
    public static function get_default_feedback_settings() {
        return array(
            'feedback_enabled'                => false,
            'request_reason_on_negative'      => true,
            'escalation_enabled'              => false,
            'escalation_support_url'          => '',
            'escalation_on_negative_feedback' => true,
            'feedback_prompt_text'            => __( 'Would you mind rating your experience with me?', 'storeagent-ai-for-woocommerce' ),
            'skip_button_text'                => __( 'Skip', 'storeagent-ai-for-woocommerce' ),
            'escalation_email_enabled'        => false,
            'escalation_email_recipient'      => '',
            'escalation_email_intro'          => __( 'A customer has requested support escalation from the AI chat.', 'storeagent-ai-for-woocommerce' ),
        );
    }

    /**
     * Validate feedback settings.
     *
     * @param array $settings Settings to validate.
     * @return bool|WP_Error True if valid, WP_Error otherwise.
     */
    public static function validate_feedback_settings( $settings ) {
        // Validate boolean fields.
        $boolean_fields = array(
            'feedback_enabled',
            'request_reason_on_negative',
            'escalation_enabled',
            'escalation_on_negative_feedback',
            'escalation_email_enabled',
        );

        foreach ( $boolean_fields as $field ) {
            if ( isset( $settings[ $field ] ) && ! is_bool( $settings[ $field ] ) ) {
                return new WP_Error(
                    'invalid_setting',
                    /* translators: %s: Field name */
                    sprintf( __( 'Invalid value for %s. Must be boolean.', 'storeagent-ai-for-woocommerce' ), $field )
                );
            }
        }

        // Validate support URL if provided.
        if ( isset( $settings['escalation_support_url'] ) && ! empty( $settings['escalation_support_url'] ) ) {
            if ( ! filter_var( $settings['escalation_support_url'], FILTER_VALIDATE_URL ) ) {
                return new WP_Error(
                    'invalid_url',
                    __( 'Invalid support URL format.', 'storeagent-ai-for-woocommerce' )
                );
            }
        }

        // Validate escalation email recipient if provided.
        if ( isset( $settings['escalation_email_recipient'] ) && ! empty( $settings['escalation_email_recipient'] ) ) {
            if ( ! is_email( $settings['escalation_email_recipient'] ) ) {
                return new WP_Error(
                    'invalid_email',
                    __( 'Invalid escalation email recipient format.', 'storeagent-ai-for-woocommerce' )
                );
            }
        }

        return true;
    }

    /**
     * Sanitize feedback settings.
     *
     * @param array $settings Settings to sanitize.
     * @return array Sanitized settings.
     */
    public static function sanitize_feedback_settings( $settings ) {
        $sanitized = array();

        // Sanitize boolean fields.
        $boolean_fields = array(
            'feedback_enabled',
            'request_reason_on_negative',
            'escalation_enabled',
            'escalation_on_negative_feedback',
            'escalation_email_enabled',
        );

        foreach ( $boolean_fields as $field ) {
            if ( isset( $settings[ $field ] ) ) {
                $sanitized[ $field ] = (bool) $settings[ $field ];
            }
        }

        // Sanitize support URL.
        if ( isset( $settings['escalation_support_url'] ) ) {
            $sanitized['escalation_support_url'] = esc_url_raw( $settings['escalation_support_url'] );
        }

        // Sanitize escalation email recipient.
        if ( isset( $settings['escalation_email_recipient'] ) ) {
            $sanitized['escalation_email_recipient'] = sanitize_email( $settings['escalation_email_recipient'] );
        }

        // Sanitize text fields.
        if ( isset( $settings['feedback_prompt_text'] ) ) {
            $sanitized['feedback_prompt_text'] = sanitize_text_field( $settings['feedback_prompt_text'] );
        }

        if ( isset( $settings['skip_button_text'] ) ) {
            $sanitized['skip_button_text'] = sanitize_text_field( $settings['skip_button_text'] );
        }

        // Sanitize escalation email intro.
        if ( isset( $settings['escalation_email_intro'] ) ) {
            $sanitized['escalation_email_intro'] = sanitize_textarea_field( $settings['escalation_email_intro'] );
        }

        return $sanitized;
    }

    /**
     * Check if escalation feature is available for current plan.
     *
     * Escalation is not available for Free and Lite plans.
     * This check is used to enforce plan-based feature restrictions.
     *
     * @since 1.0.0
     * @return bool True if escalation is available (paid plans), false otherwise (free/lite plans or no plan data).
     */
    public static function is_escalation_available() {
        // Get current plan from Plan_Manager.
        $plan_manager = \SAAI\Classes\Plan_Manager::instance();
        $plan_data    = $plan_manager->get_plan_data();

        if ( empty( $plan_data ) || empty( $plan_data['plan_name'] ) || ! is_string( $plan_data['plan_name'] ) ) {
            return false;
        }

        $plan_name = $plan_data['plan_name'];

        // Escalation not available for free or lite plans.
        // Use word boundary regex to avoid false positives (e.g., "Freelancer" or "Satellite").
        if ( preg_match( '/\b(free|lite)\b/i', $plan_name ) ) {
            return false;
        }

        return true;
    }

    /**
     * Get feedback settings filtered by current plan.
     *
     * Returns feedback settings with escalation options filtered out
     * for free/lite plans to enforce business logic at the data layer.
     *
     * @since 1.0.0
     * @return array Filtered feedback settings. For free/lite plans, escalation_enabled is set to false
     *               and escalation-related keys (escalation_support_url, escalation_on_negative_feedback) are removed.
     */
    public static function get_feedback_settings_for_plan() {
        $settings = self::get_feedback_settings();

        // Ensure we have valid settings array.
        if ( ! is_array( $settings ) ) {
            return array();
        }

        // Filter escalation settings for free/lite plans.
        if ( ! self::is_escalation_available() ) {
            $settings['escalation_enabled']       = false;
            $settings['escalation_email_enabled'] = false;
            unset( $settings['escalation_support_url'] );
            unset( $settings['escalation_on_negative_feedback'] );
            unset( $settings['escalation_email_recipient'] );
            unset( $settings['escalation_email_intro'] );
        }

        return $settings;
    }
}
