<?php
/**
 * Setup API handler for setup wizard (v1.0 WebRTC only).
 *
 * NOTE: This file previously handled v2.0 phone webhooks.
 * All legacy phone webhook methods have been removed. v1.0 WebRTC endpoints are in
 * class-sitestaffr-rest-api.php instead.
 *
 * Renamed from class-sitestaffr-webhook.php to class-sitestaffr-setup-api.php
 * to accurately reflect its purpose (setup wizard API only, not webhooks).
 *
 * @link       https://github.com/sitestaffr/sitestaffr-plugin
 * @since      1.0.0
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/includes
 */

/**
 * Setup API handler for setup wizard.
 *
 * Handles REST API endpoints for the setup wizard only.
 * All v2.0 legacy phone webhook code has been removed.
 *
 * @since      1.0.0
 * @package    SiteStaffr
 * @subpackage SiteStaffr/includes
 * @author     SiteStaffr
 */
class SiteStaffr_Setup_API {

	/**
	 * Maximum allowed length for business description.
	 *
	 * @since 0.14.151
	 */
	const BUSINESS_DESCRIPTION_MAX_LENGTH = 5000;

	/**
	 * Register REST API routes.
	 *
	 * Only registers setup wizard endpoints. All legacy v2.0 routes removed.
	 *
	 * @since    1.0.0
	 */
	public function register_routes() {
		// Setup Wizard REST endpoints
		register_rest_route( 'sitestaffr/v1', '/setup-wizard', array(
			'methods'             => 'POST',
			'callback'            => array( $this, 'handle_setup_wizard' ),
			'permission_callback' => array( $this, 'validate_admin_request' ),
		) );

		register_rest_route( 'sitestaffr/v1', '/setup-status', array(
			'methods'             => 'GET',
			'callback'            => array( $this, 'get_setup_status' ),
			'permission_callback' => array( $this, 'validate_admin_request' ),
		) );
	}

	/**
	 * Validate that the request came from an authorized WordPress admin.
	 *
	 * @since    1.0.0
	 * @param    WP_REST_Request    $request    The REST API request.
	 * @return   bool                           True if valid, false otherwise.
	 */
	public function validate_admin_request( $request ) {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Get setup wizard completion status.
	 *
	 * @since    1.0.0
	 * @param    WP_REST_Request    $request    The REST API request.
	 * @return   WP_REST_Response               JSON response with setup status.
	 */
	public function get_setup_status( $request ) {
		$is_complete = SiteStaffr_Admin::is_setup_complete();
		$settings = get_option( 'sitestaffr_settings', array() );

		return new WP_REST_Response( array(
			'setup_complete'     => $is_complete,
			'business_name'      => isset( $settings['business_name'] ) ? $settings['business_name'] : '',
			'has_ai_configured'  => true, // v1.0: AI is SiteStaffr infrastructure, always configured
			'has_phone_number'   => false, // v1.0: No phone provisioning (v2.0 feature)
		), 200 );
	}

	/**
	 * Handle setup wizard data submission.
	 *
	 * Validates and saves wizard data to the sitestaffr_settings option.
	 *
	 * @since    1.0.0
	 * @param    WP_REST_Request    $request    The REST API request.
	 * @return   WP_REST_Response               JSON response.
	 */
	public function handle_setup_wizard( $request ) {
		// Get parameters
		$params = $request->get_json_params();

		// If JSON params empty, try regular params
		if ( empty( $params ) ) {
			$params = $request->get_params();
		}

		// Validate required fields
		$validation = $this->validate_wizard_data( $params );
		if ( is_wp_error( $validation ) ) {
			return new WP_REST_Response( array(
				'success' => false,
				'message' => $validation->get_error_message(),
				'errors'  => $validation->get_error_data(),
			), 400 );
		}

		// Get existing settings
		$settings = get_option( 'sitestaffr_settings', array() );

		// Sanitize and save wizard data
		$settings['business_name'] = sanitize_text_field( $params['business_name'] );
		$settings['business_context'] = sanitize_textarea_field( $params['business_description'] ?? '' );
		$settings['business_phone'] = $this->sanitize_phone_number( $params['business_phone'] ?? '' );
		$settings['business_hours_type'] = sanitize_text_field( $params['business_hours_type'] ?? '24_7' );
		$settings['custom_hours'] = sanitize_text_field( $params['custom_hours'] ?? '' );
		$posted_notification_email      = isset( $params['notification_email'] ) ? $params['notification_email'] : '';
		$settings['notification_email'] = SiteStaffr_Account_Contact::resolve_notification_email_for_save(
			$posted_notification_email,
			$settings
		);

		// Generate business hours text based on selection
		switch ( $settings['business_hours_type'] ) {
			case '24_7':
				$settings['business_hours'] = '24/7';
				break;
			case 'business_hours':
				$settings['business_hours'] = 'Monday-Friday 9am-5pm';
				break;
			case 'custom':
				$settings['business_hours'] = $settings['custom_hours'];
				break;
			default:
				$settings['business_hours'] = '24/7';
		}

		// Mark setup as complete
		$settings['setup_complete'] = true;
		$settings['setup_completed_at'] = current_time( 'mysql' );

		// Update settings
		$updated = update_option( 'sitestaffr_settings', $settings );

		if ( $updated || get_option( 'sitestaffr_settings' ) === $settings ) {
			/** This action is documented in admin/class-sitestaffr-admin.php */
			do_action( 'sitestaffr_setup_wizard_completed' );

			return new WP_REST_Response( array(
				'success' => true,
				'message' => __( 'Setup wizard completed successfully.', 'sitestaffr' ),
				'data'    => array(
					'business_name'      => $settings['business_name'],
					'business_hours'     => $settings['business_hours'],
					'notification_email' => $settings['notification_email'],
				),
			), 200 );
		}

		return new WP_REST_Response( array(
			'success' => false,
			'message' => __( 'Failed to save settings. Please try again.', 'sitestaffr' ),
		), 500 );
	}

	/**
	 * Validate wizard data.
	 *
	 * @since    1.0.0
	 * @param    array    $data    Wizard data to validate.
	 * @return   true|WP_Error     True if valid, WP_Error if invalid.
	 */
	private function validate_wizard_data( $data ) {
		$errors = array();

		// Required: Business name
		if ( empty( $data['business_name'] ) ) {
			$errors['business_name'] = __( 'Business name is required.', 'sitestaffr' );
		} elseif ( strlen( $data['business_name'] ) > 100 ) {
			$errors['business_name'] = __( 'Business name must be less than 100 characters.', 'sitestaffr' );
		}

		$existing_settings             = get_option( 'sitestaffr_settings', array() );
		$resolved_notification_email   = SiteStaffr_Account_Contact::resolve_notification_email_for_save(
			isset( $data['notification_email'] ) ? $data['notification_email'] : '',
			$existing_settings
		);

		// Required: Notification email (must resolve to a valid address)
		if ( empty( $resolved_notification_email ) ) {
			$errors['notification_email'] = __( 'Email address is required.', 'sitestaffr' );
		} elseif ( ! is_email( $resolved_notification_email ) ) {
			$errors['notification_email'] = __( 'Please enter a valid email address.', 'sitestaffr' );
		}

		// Optional but validate if provided: Business phone
		if ( ! empty( $data['business_phone'] ) ) {
			$phone_digits = preg_replace( '/\D/', '', $data['business_phone'] );
			if ( strlen( $phone_digits ) < 10 || strlen( $phone_digits ) > 15 ) {
				$errors['business_phone'] = __( 'Please enter a valid phone number (10-15 digits).', 'sitestaffr' );
			}
		}

		// Optional but validate if provided: Business description
		if ( ! empty( $data['business_description'] ) && strlen( $data['business_description'] ) > self::BUSINESS_DESCRIPTION_MAX_LENGTH ) {
			$errors['business_description'] = sprintf(
				/* translators: %d is the max business description length */
				__( 'Business description must be less than %d characters.', 'sitestaffr' ),
				self::BUSINESS_DESCRIPTION_MAX_LENGTH
			);
		}

		// Validate business_hours_type against whitelist
		$allowed_hours_types = array( '24_7', 'business_hours', 'custom' );
		if ( isset( $data['business_hours_type'] ) && ! in_array( $data['business_hours_type'], $allowed_hours_types, true ) ) {
			$errors['business_hours_type'] = __( 'Invalid business hours type.', 'sitestaffr' );
		}

		// Validate hours type if custom is selected
		if ( isset( $data['business_hours_type'] ) && $data['business_hours_type'] === 'custom' ) {
			if ( empty( $data['custom_hours'] ) ) {
				$errors['custom_hours'] = __( 'Please enter your custom hours.', 'sitestaffr' );
			}
		}

		if ( ! empty( $errors ) ) {
			return new WP_Error( 'validation_failed', __( 'Please correct the errors below.', 'sitestaffr' ), $errors );
		}

		return true;
	}

	/**
	 * Sanitize phone number to standard format.
	 *
	 * @since    1.0.0
	 * @param    string    $phone    Phone number to sanitize.
	 * @return   string              Sanitized phone number.
	 */
	private function sanitize_phone_number( $phone ) {
		// Remove all non-digits except + for international numbers
		$cleaned = preg_replace( '/[^\d+]/', '', $phone );

		// If it starts with 1 and has 11 digits, format as US number
		if ( strlen( $cleaned ) === 11 && substr( $cleaned, 0, 1 ) === '1' ) {
			return '+' . $cleaned;
		}

		// If 10 digits, assume US and add +1
		if ( strlen( $cleaned ) === 10 ) {
			return '+1' . $cleaned;
		}

		// Otherwise return as-is with + prefix if not present
		if ( ! empty( $cleaned ) && substr( $cleaned, 0, 1 ) !== '+' ) {
			return '+' . $cleaned;
		}

		return $cleaned;
	}
}
