<?php
/**
 * Fraud Module — Phone Validator (Checkout format validation only).
 *
 * Validates billing phone format at checkout.
 * Rate limiting, risk scoring, and CAPI gating are handled exclusively
 * by Pro modules (Fraud_Gating + Blacklist_Manager).
 *
 * FREE plugin has NO capiflow_is_order_gated filter — all CAPI fires
 * unconditionally. Pro registers its own filter at priority 20.
 *
 * Changes from old version:
 * - Removed: calculate_risk_score() — moved to Pro Reputation Engine
 * - Removed: get_phone_stats() — moved to Pro Reputation Engine
 * - Removed: is_disposable_email() — moved to Pro Blacklist_Manager
 * - Removed: is_phone_rate_limited() — moved to Pro Blacklist_Manager frequency
 * - Removed: is_ip_rate_limited() — moved to Pro Blacklist_Manager frequency
 * - Removed: get_recent_order_count_for_phone() — moved to Pro Blacklist_Manager
 * - Removed: check_order_risk() — Pro Fraud_Gating handles CAPI gating
 * - Removed: _capiflow_risk_score meta write — Pro writes _capiflow_reputation_level
 * - Removed: capiflow_order_risk_scored action — obsolete
 * - Removed: capiflow_fraud_threshold filter — obsolete
 * - Kept: validate_checkout_phone() — basic phone format validation (data quality)
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core\Modules\Fraud;

defined( 'ABSPATH' ) || exit;

class Phone_Validator {

	/**
	 * Boot the fraud module — called by capiflow_module_loaded_fraud action.
	 *
	 * Registers ONLY checkout phone format validation.
	 * No CAPI gating, no rate limiting — those are Pro features.
	 */
	public static function init(): void {
		$instance = new self();

		// Checkout phone format validation only.
		add_action( 'woocommerce_checkout_process', array( $instance, 'validate_checkout_phone' ) );
	}

	/**
	 * Validate phone number format at checkout.
	 *
	 * Fires wc_add_notice() to block submission if phone format is invalid.
	 * No rate limiting here — Pro's Blacklist_Manager handles frequency limits.
	 */
	public function validate_checkout_phone(): void {
		// Nonce is verified by WooCommerce core in WC_Checkout::process_checkout().
		$phone = sanitize_text_field( wp_unslash( $_POST['billing_phone'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing

		if ( empty( $phone ) ) {
			return;
		}

		$normalized = \CapiFlow\Core\Data_Normalizer::normalize_phone_e164( $phone );

		// Basic format validation.
		if ( strlen( $normalized ) < 10 || strlen( $normalized ) > 15 ) {
			wc_add_notice( __( 'Please enter a valid phone number.', 'capiflow' ), 'error' );
		}
	}
}

// Auto-init when module loads via Plugin_Loader::load_module('fraud').
add_action( 'capiflow_module_loaded_fraud', array( 'CapiFlow\Core\Modules\Fraud\Phone_Validator', 'init' ) );
