<?php
/**
 * Business settings AJAX handlers for SiteStaffr admin.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/traits
 * @since      0.14.264
 */

if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Encapsulates business profile/settings AJAX actions.
 */
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Raw request values are immediately unslashed and sanitized via dedicated validators/sanitizers.
trait SiteStaffr_Admin_Business_Settings_Ajax_Trait {

	/**
	 * AJAX: Settings → Account & Connection middleware health check.
	 *
	 * @since 1.34.0
	 * @return void
	 */
	public function ajax_test_mw_connection() {
		if ( ! check_ajax_referer( 'sitestaffr_admin_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to do this.', 'sitestaffr' ) ) );
			return;
		}

		$middleware_url = defined( 'SITESTAFFR_MIDDLEWARE_URL' )
			? SITESTAFFR_MIDDLEWARE_URL
			: get_option( 'sitestaffr_middleware_url', '' );

		if ( empty( $middleware_url ) ) {
			wp_send_json_error( array( 'message' => __( 'No service URL is configured.', 'sitestaffr' ) ) );
			return;
		}

		$started  = microtime( true );
		$response = wp_remote_get( trailingslashit( $middleware_url ) . 'health', array( 'timeout' => 10 ) );
		$latency  = (int) round( ( microtime( true ) - $started ) * 1000 );

		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array(
				/* translators: %s: connection error detail. */
				'message' => sprintf( __( 'Could not reach the SiteStaffr service (%s).', 'sitestaffr' ), $response->get_error_message() ),
			) );
			return;
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			wp_send_json_error( array(
				/* translators: %d: HTTP status code. */
				'message' => sprintf( __( 'Service responded with HTTP %d.', 'sitestaffr' ), $code ),
			) );
			return;
		}

		wp_send_json_success( array(
			/* translators: %d: round-trip time in milliseconds. */
			'message' => sprintf( __( 'Connected — service healthy (%dms).', 'sitestaffr' ), $latency ),
		) );
	}

	/**
	 * AJAX handler to save all Business Information fields from the Settings page.
	 *
	 * Handles the Business Name, Business Phone, Business Description, Business Hours,
	 * and AI Voice fields in a single AJAX request, replacing the WP Settings API
	 * form POST to options.php.
	 *
	 * @since 0.14.88
	 * @return void
	 */
	public function ajax_save_business_settings() {
		if ( ! check_ajax_referer( 'sitestaffr_admin_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to do this.', 'sitestaffr' ) ) );
			return;
		}

		// --- Sanitize inputs ---
		$business_name = isset( $_POST['business_name'] )
			? sanitize_text_field( wp_unslash( $_POST['business_name'] ) )
			: '';
		$business_name = trim( $business_name );

		if ( '' === $business_name ) {
			wp_send_json_error(
				array(
					'message' => __( 'Business name is required.', 'sitestaffr' ),
				)
			);
			return;
		}

		$business_phone = isset( $_POST['business_phone'] )
			? sanitize_text_field( wp_unslash( $_POST['business_phone'] ) )
			: '';

		$business_context_raw = isset( $_POST['business_context'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized by sanitize_business_description().
			? wp_unslash( $_POST['business_context'] )
			: '';
		$description_result   = $this->sanitize_business_description( $business_context_raw );
		$business_context     = $description_result['value'];

		// Detailed Business Profile body — stored body-only (summary lives in business_context).
		// Strip any leading SUMMARY defensively so it is never duplicated.
		$business_profile_raw = isset( $_POST['business_profile'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized below.
			? wp_unslash( $_POST['business_profile'] )
			: '';
		$business_profile = self::strip_summary_section( sanitize_textarea_field( $business_profile_raw ) );
		if ( strlen( $business_profile ) > self::BUSINESS_PROFILE_BODY_MAX_LENGTH ) {
			$business_profile = substr( $business_profile, 0, self::BUSINESS_PROFILE_BODY_MAX_LENGTH );
		}

		$plan_key               = $this->get_current_plan_key();
		$custom_greeting_result = array(
			'value'     => '',
			'truncated' => false,
		);
		$custom_greeting_tone = self::CUSTOM_GREETING_TONE_DEFAULT;
		if ( $this->is_custom_greeting_allowed_for_plan( $plan_key ) ) {
			$custom_greeting_raw    = isset( $_POST['custom_greeting'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized by sanitize_custom_greeting().
				? wp_unslash( $_POST['custom_greeting'] )
				: '';
			$custom_greeting_result = $this->sanitize_custom_greeting( $custom_greeting_raw );
			$custom_greeting_tone_raw = isset( $_POST['custom_greeting_tone'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized by sanitize_custom_greeting_tone().
				? wp_unslash( $_POST['custom_greeting_tone'] )
				: self::CUSTOM_GREETING_TONE_DEFAULT;
			$custom_greeting_tone = $this->sanitize_custom_greeting_tone( $custom_greeting_tone_raw );
		}
		$custom_greeting = $custom_greeting_result['value'];

		$business_hours_raw = isset( $_POST['business_hours'] )
			? sanitize_text_field( wp_unslash( $_POST['business_hours'] ) )
			: '';
		$hours_validation = $this->validate_business_hours( $business_hours_raw );

		if ( ! $hours_validation['valid'] ) {
			wp_send_json_error( array( 'message' => $hours_validation['error'] ) );
			return;
		}
		$business_hours = $hours_validation['sanitized'];

		$valid_voices = array(
			'marin',
			'cedar',
			'alloy',
			'ash',
			'coral',
			'echo',
			'sage',
			'shimmer',
			'ballad',
			'verse',
		);
		$ai_voice_raw = isset( $_POST['ai_voice'] )
			? sanitize_text_field( wp_unslash( $_POST['ai_voice'] ) )
			: 'marin';
		$ai_voice = in_array( $ai_voice_raw, $valid_voices, true ) ? $ai_voice_raw : 'marin';

		// Enforce plan-based voice gating.
		$plan_allowed_voices = SiteStaffr_Admin::get_voices_for_plan( $plan_key );
		if ( ! in_array( $ai_voice, $plan_allowed_voices, true ) ) {
			// Silently fall back to current saved voice or default.
			$current_settings = get_option( 'sitestaffr_settings', array() );
			$ai_voice         = isset( $current_settings['ai_voice'] ) && in_array( $current_settings['ai_voice'], $plan_allowed_voices, true )
				? $current_settings['ai_voice']
				: 'marin';
		}

		// --- Persist standalone options (mirrors sanitize_settings behavior) ---
		update_option( 'sitestaffr_business_phone', $business_phone );
		self::save_business_description_option( $business_context );
		update_option( 'sitestaffr_business_hours', $business_hours );

		$widget_settings = get_option( 'sitestaffr_widget_settings', array() );
		if ( ! is_array( $widget_settings ) ) {
			$widget_settings = array();
		}
		$widget_settings['ai_voice'] = $ai_voice;
		update_option( 'sitestaffr_widget_settings', $widget_settings );

		// --- Merge into sitestaffr_settings option ---
		$settings = get_option( 'sitestaffr_settings', array() );
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		$settings['business_name']         = $business_name;
		$settings['business_phone']        = $business_phone;
		$settings['business_context']      = $business_context;
		$settings['business_profile']      = $business_profile;
		$settings['business_hours']        = $business_hours;
		$settings['custom_greeting']       = $custom_greeting;
		$settings['custom_greeting_tone']  = $custom_greeting_tone;
		$settings['ai_voice']              = $ai_voice;

		update_option( 'sitestaffr_settings', $settings );

		wp_send_json_success(
			array(
				'message' => $custom_greeting_result['truncated']
					? sprintf(
						/* translators: %d is the max custom greeting length */
						__( 'Business settings saved. Custom greeting was trimmed to %d characters.', 'sitestaffr' ),
						self::CUSTOM_GREETING_MAX_LENGTH
					)
					: __( 'Business settings saved.', 'sitestaffr' ),
			)
		);
	}

	/**
	 * AJAX handler for updating AI receptionist voice selection.
	 *
	 * Saves voice selection to both main settings and widget settings so
	 * frontend widgets and admin Settings stay synchronized.
	 *
	 * @since 0.14.106
	 * @return void
	 */
	public function ajax_update_ai_voice() {
		if ( ! check_ajax_referer( 'sitestaffr_admin_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'sitestaffr' ) ) );
			return;
		}

		$ai_voice       = isset( $_POST['ai_voice'] ) ? sanitize_text_field( wp_unslash( $_POST['ai_voice'] ) ) : '';
		$allowed_voices = array( 'marin', 'cedar', 'alloy', 'ash', 'coral', 'echo', 'sage', 'shimmer', 'ballad', 'verse' );

		if ( empty( $ai_voice ) || ! in_array( $ai_voice, $allowed_voices, true ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid voice selection.', 'sitestaffr' ) ) );
			return;
		}

		// Plan-based voice gating.
		$plan_key        = '';
		if ( class_exists( 'SiteStaffr_Billing_State' ) ) {
			$billing_cache = SiteStaffr_Billing_State::get_cache();
			$plan_key      = isset( $billing_cache['plan_name'] ) ? sanitize_key( $billing_cache['plan_name'] ) : '';
		}
		if ( empty( $plan_key ) ) {
			$subscription = get_option( 'sitestaffr_subscription', array() );
			if ( is_array( $subscription ) ) {
				$plan_key = isset( $subscription['plan_name'] ) ? sanitize_key( $subscription['plan_name'] ) : '';
			}
		}
		if ( empty( $plan_key ) ) {
			$plan_key = 'trial';
		}
		$plan_allowed = SiteStaffr_Admin::get_voices_for_plan( $plan_key );
		if ( ! in_array( $ai_voice, $plan_allowed, true ) ) {
			$required_plan = SiteStaffr_Admin::get_required_plan_for_voice( $ai_voice );
			wp_send_json_error(
				array(
					'message' => sprintf(
						/* translators: %s is the required plan name */
						__( 'This voice requires the %s plan. Please upgrade to use it.', 'sitestaffr' ),
						ucfirst( $required_plan )
					),
				)
			);
			return;
		}

		$settings             = get_option( 'sitestaffr_settings', array() );
		$settings['ai_voice'] = $ai_voice;
		update_option( 'sitestaffr_settings', $settings );

		$widget_settings             = get_option( 'sitestaffr_widget_settings', array() );
		$widget_settings['ai_voice'] = $ai_voice;
		update_option( 'sitestaffr_widget_settings', $widget_settings );

		wp_send_json_success(
			array(
				'message'  => __( 'Voice updated.', 'sitestaffr' ),
				'ai_voice' => $ai_voice,
			)
		);
	}

	/**
	 * AJAX handler to save enhancement data from setup wizard Step 4.
	 *
	 * Saves business hours and description to WordPress options.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajax_save_enhancement() {
		// Verify nonce
		if ( ! check_ajax_referer( 'sitestaffr_setup_wizard', 'nonce', false ) ) {
			SiteStaffr_Logger::legacy( 'SiteStaffr Enhancement: Nonce verification failed' );
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'sitestaffr' ) ) );
			return;
		}

		// Verify capability
		if ( ! current_user_can( 'manage_options' ) ) {
			SiteStaffr_Logger::legacy( 'SiteStaffr Enhancement: Permission denied' );
			wp_send_json_error( array( 'message' => __( 'You do not have permission to do this.', 'sitestaffr' ) ) );
			return;
		}

		// Get and sanitize inputs
		$hours       = isset( $_POST['business_hours'] ) ? sanitize_text_field( wp_unslash( $_POST['business_hours'] ) ) : '';
		$description = isset( $_POST['business_description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['business_description'] ) ) : '';

		if ( strlen( $description ) > self::BUSINESS_DESCRIPTION_MAX_LENGTH ) {
			wp_send_json_error(
				array(
					'message' => sprintf(
						/* translators: %d is the max business description length */
						__( 'Business description is too long. Maximum %d characters.', 'sitestaffr' ),
						self::BUSINESS_DESCRIPTION_MAX_LENGTH
					),
				)
			);
			return;
		}

		// Validate business hours BEFORE saving
		if ( ! empty( $hours ) ) {
			$validation = $this->validate_business_hours( $hours );
			if ( ! $validation['valid'] ) {
				SiteStaffr_Logger::legacy( 'SiteStaffr: Business hours validation FAILED in AJAX handler: ' . $validation['error'] );
				wp_send_json_error( array( 'message' => $validation['error'] ) );
				return;
			}
			// Use sanitized value from validation
			$hours = $validation['sanitized'];
		}

		// Get settings array ONCE to avoid race conditions
		$settings = get_option( 'sitestaffr_settings', array() );

		// Save business hours to standalone option AND settings array
		if ( ! empty( $hours ) ) {
			update_option( 'sitestaffr_business_hours', $hours );
			$settings['business_hours'] = $hours;
		}

		// Save business description to standalone option AND settings array
		if ( ! empty( $description ) ) {
			self::save_business_description_option( $description );
			$settings['business_context'] = $description;
		}

		// Save settings array once with both values
		update_option( 'sitestaffr_settings', $settings );

		wp_send_json_success(
			array(
				'message'     => __( 'Enhancement data saved successfully', 'sitestaffr' ),
				'hours'       => $hours,
				'description' => $description,
			)
		);
	}
}
// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
